Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC inject per request

I need to inject EF context per request. Is there any way to implement it?

like image 450
SiberianGuy Avatar asked Oct 10 '10 06:10

SiberianGuy


People also ask

What is dependency injection in ASP.NET MVC?

The Dependency Injection pattern is a particular implementation of Inversion of Control. Inversion of Control (IoC) means that objects do not create other objects on which they rely to do their work. Instead, they get the objects that they need from an outside source (for example, an xml configuration file).

How can we inject the service dependency into the controller?

ASP.NET Core injects objects of dependency classes through constructor or method by using built-in IoC container. The built-in container is represented by IServiceProvider implementation that supports constructor injection by default.


2 Answers

Did you check out this excellent blog on DI with Unity and ASP.NET MVC?

Should get you on the right track.

The answer is yes, you can - and the article shows you how.

In short, you create a HttpContextLifetimeManager to handle the "scoping" of your objects. The container "caches" the instance in the HTTP Context.

This is needed because the default life time managers provided by Unity don't cover HTTP Context scoping "off the shelf".

Of course, other DI container's (such as StructureMap - which i use), do.

Here is another (more up to date) article on the same thing, with the "Nerdinner" as the example.

like image 51
RPM1984 Avatar answered Nov 15 '22 11:11

RPM1984


The solution proposed in the Unity Discussion list is to create a child container per request, have that child container create the EF context as ContainerControlledLifetime, then have the child container disposed at the end of the request. By doing so you don't have to create a custom LifetimeManager.

I'm not very familiar with Unity but the principle would be something like this:

Application_BeginRequest(...)
{
  var childContainer = _container.CreateChildContainer();
  HttpContext.Items["container"] = childContainer;
  childContainer.RegisterType<ObjectContext, MyContext>
     (new ContainerControlledLifetimeManager());
}

Application_EndRequest(...)
{
  var container = HttpContext.Items["container"] as IUnityContainer
  if(container != null)
    container.Dispose();
}
like image 27
PHeiberg Avatar answered Nov 15 '22 11:11

PHeiberg