0

I have Windows service accepting some messages. I use LightInject for DI. The service writes into database via dbContext every time any message comes. Thus I need to limit dbContext's lifetime to handling of that message and dispose it once the message is handled. I wonder if creating my own scope per message would be the way. But I struggle to find out how to cleanly do it.

I have there some listener which makes handler handle every received message. And I need to create scope on message received event. But as it is in existing instance of the consumer, I have no container there on which I could begin the new scope. And I cannot inject the container itself, as it is bad practice and simply doesn't work. So is there any way how to create new scope on my custom event anywhere outside Composition Root?

I would need something like this:

Service root:

serviceRegistry.Register<IMessageConsumer, CreateUserMessageConsumer>(
    new PerContainerLifetime());
serviceRegistry.Register<RequestHandler, UserCreateHandler>(
    new PerScopeLifetime());
serviceRegistry.Register<DbContext, MyDbContext>(
    new PerScopeLifetime());

Consumer:

CreateUserMessageConsumer(CreateUserHandler handler)
{
    this.handler = handler;
}

public async Listen()
{
    //listening producing message
    ....
    using(container.BeginScope())    //this is the problematic part
    {
        this.handler.Handle(message);
    }       
}

Handler:

CreateUserHandler(DbContext context)
{
    this.dbContext = context;
}
    
public void Handle(Message message)
{
    //do some db magic with dbContext
}
Steven
  • 166,672
  • 24
  • 332
  • 435
Qerts
  • 935
  • 1
  • 15
  • 29
  • Creating a new isolated bubble (i.e. scope) per message is a good idea. This prevents messages from being able to influence each other based on shared state. Having this shared state makes the system really hard to test and verify. – Steven Feb 24 '21 at 13:13
  • Your question doesn't include information on the used messaging framework. How to wrap your container's scope and the resolving of a message handler is highly dependent on the interception points that the used messaging framework provides. – Steven Feb 24 '21 at 13:15

0 Answers0