Search code examples
c#asp.net-mvcentity-frameworksimple-injector

Simple Injector for Unit Of Work and EF DbContext per Request


I'm using the UoW pattern and i've used Simple Injector to dependency injection. I've registered the UoW class like container.Register<IUnitOfWork, UnitOfWork>(Lifestyle.Scoped); and the UoW class receives a DbContext in the constructor like:

    private readonly LPCContext _lpcContext;        

    public UnitOfWork(LPCContext lpcContext)
    {
        _lpcContext = lpcContext;
    }

Where LpcContext is a DbContext type.

My question is: Since i want to have a DbContext per request, do i still need to register it in Simple Injector? If so, how do i achieve this?


Solution

  • If LPCContext is a concrete type with a single constructor, technically speaking, you don't have to register it, because Simple Injector can auto-create it for you, and since the UnitOfWork is created as scoped, it will drag allong the LPCContext as scoped lifestyle as well. However...

    Simple Injector will auto-register a concrete unregistered type for you using the transient lifestyle. But now your scoped registration of UnitOfWork depends on a registration with a shorer lifestyle (transient), Simple Injector will throw an exception, explaining there is a Lifestyle Mismatch.

    Although in your particular case this wouldn't be a problem per see, it is still important to fix the problem, because it can easily lead to problems later on, when you start injecting the LPCContext into other consumers as well. In that case, each consumer will get its own LPCContext instance, which is typically not what you want.

    So to solve this, it's best to register the LPCContext class explicitly using the scoped lifestyle:

    string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    container.Register<LPCContext>(() => new LPCContext(conString), Lifestyle.Scoped);