Maxim V. Pavlov
Maxim V. Pavlov

Reputation: 10509

Instantiating a DbContext in a repository instance

In ASP.NET MVC3 application, my controllers will work with the set of BL "manager" classes, which, in turn, will make use of repositories. These repositories rely on EF DbContext instances to perform its duties.

I am planning to configure IoC container to do a dependency injection the following way (in data module)

Bind<StoreContext>().ToSelf().InRequestScope();
Bind<ICatUserRepository>().To<GenericUserRepository>().InRequestScope();

StoreContext is a DbContext. It is constructor-injected into a GenericUserRepository. This way, I assume, the rule of my DbContext to be instantiated in also PerRequest will remain fulfilled, right?

Upvotes: 2

Views: 477

Answers (1)

BrokenGlass
BrokenGlass

Reputation: 160852

Yes it certainly would be - since ICatUserRepository is resolved on a request scope level the IoC container will at that point (for each request) create a new instance of GenericUserRepository after resolving its dependencies for constructor injection.

Resolving the the StoreContext dependency means the IoC container will go through the binding for StoreContext, check if there already is an existing instance of StoreContext for the current request and if not create a fresh copy to inject - In your case that means you get a new instance of StoreContext for each new request.

Upvotes: 1

Related Questions