Simple Injector LifetimeScope with DbContext

373 views Asked by At

I am using simpleInjector 2.8.0.0 I would like to construct just one instance of a dbContext during a lifetime scope. (My dependency chain has 2 dependencies on IDatabaseContext/DbContext)

I have a scope decorator which implements the lifetime scope (The scope decorator is being injected into a SignalRHub):

  using (ServiceHost.Container.BeginLifetimeScope())
        {
            var commandHandler = ServiceHost.Container.GetInstance<ICommandHandler<TCommand>>();
       //constructs 2 DbContexts.
            commandHandler.Handle(command);
        }

I have a lifetime scope registration for the IDatabaseContext:

        container.RegisterLifetimeScope<IDatabaseContext, DatabaseContext>();

However, I can see (from a Guid) that I am creating 2 instances of the IDatabaseContext/DbContext within the scope.

1

There are 1 answers

0
Steven On BEST ANSWER

Are you sure this is the same scope? Either you are nesting scopes, or you what you see is two actual request being handled. In the debugger, you might be able to view request information, for instance by inspecting the HttpContext.Current.Request.Url property.