Bartosz
Bartosz

Reputation: 4766

Is dependency injected DbContext shared between all classes that use it within a given request instance?

I am wondering how exactly does Ninject handle EF DbContext injection is the following scenario.

There is a utility class that takes DbContext as argument and does some work which requires dbContext:

public class SomeClass : ISomeClass
{
    public SomeClass(MyDbContext context)
    {
        //the context is dependency injected
    }
}

There is an API controller that takes DbContext as well as an injected instance of ISomeClass (which also requires DbContext)

    public class SomeController
    {

        public SomeController(MyDbContext context, ISomeClass someClass)
        {
            //this controller uses db context for some simple actions and someclass for some more complex actions
        }
    }

Binding option set to:

kernel.Bind<MyDbContext>().ToSelf().InRequestScope();

Now, the questions is

When SomeController is instantiated, does the instance of SomeClass share the same instance of MyDbContext? Also, if SomeClass had SomeSubClass injected which also had MyDbContext injected into constructor, would that be the same context instance?

Does it work like that:

An http request comes in and requires creating controller and its dependencies that require DbContext, so since we are set to InRequestScope, lets return the same instance to rule them all?

If so, then there is no difference (DbContext wise) between a controller constructor which takes the context and creates UnitOfWork classes (pattern from here) like that

public class SomeController(MyDbContext context)
{
   this.someUnitOfWork = new SomeUnitOfWork(context);
}

and one that takes the unit of work as injected parameter

public class SomeController(MyDbContext context, ISomeUnitOfWork someUnit){}

And here, the only difference would be the tight coupling to SomeUnitOfWork implementation?

Upvotes: 4

Views: 693

Answers (1)

mjwills
mjwills

Reputation: 23820

An http request comes in and requires creating controller and its dependencies that require DbContext, so since we are set to InRequestScope, lets return the same instance to rule them all?

Yes. That is what InRequestScope does.

https://github.com/ninject/Ninject.Web.Common/wiki/InRequestScope has all the fun details:

The main reason for using InRequestScope() is to make sure that a single instance of an object is shared by all objects created via the Ninject kernel for that HTTP request (e.g. to share an object that is expensive to create).

Upvotes: 3

Related Questions