Qerts
Qerts

Reputation: 1005

Lightinject - how to safely begin new scope outsice composition root?

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
}

Upvotes: 0

Views: 206

Answers (0)

Related Questions