Using the Unity IOC to inject dbcontext into my controllers and service layer?

asp.net asp.net-mvc entity-framework entity-framework-6 unity-container

Question

How can I inject my dbcontext into the service layer with the Unity IOC. In particular I want to be sure that I only have the one dbcontext and I want to ensure this is destroyed at the right time even if I am using async.

My application uses EF6 and a Generic repository. There's a lot of code there and I have decided I would like to remove the Generic repository, use EF6 context as my UOW and dbsets as my Repositories. This would appear to be the approach recommended by a number of the more experienced developers here on SO. Bear in mind I do not want to change my ORM, database. The application has less than 20 tables and I have many ways that I can test it without using another repository.

1
1
2/18/2014 4:59:43 AM

Popular Answer

I'm not sure what you mean by injecting your DB context into your "service layer," but assuming you meant an ASP.NET MVC website based on the tags, you'll just want to set up your container with the global DependencyResolver class and make sure your contexts are set to request lifetime with the PerRequestLifetimeManager.

You can find a good breakdown of dependency injection in MVC here.

0
2/19/2014 4:04:15 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow