ASP.NET MVC for each request

I need to enter an EF context for each request. Is there any way to implement it?

+5
c # dependency-injection asp.net-mvc unity-container
Oct 10 2018-10-10T00:
source share
3 answers

The proposed solution in the Unity Discussion list is to create a child container for each request so that this child container creates an EF context as ContainerControlledLifetime, then enter the child container at the end of the request. By doing so, you do not need 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(); } 
+5
Oct 10 '10 at 8:26
source share

Have you checked out this great DI blog with Unity and ASP.NET MVC?

It should turn out on the right track.

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

In short, you create an HttpContextLifetimeManager to handle the "scope" of your objects. The container "caches" the instance in an HTTP context.

This is necessary because the default lifetime managers provided by Unity do not cover the scope of the HTTP context from the shelf.

Of course, another DI container (such as StructureMap - which I use) does.

Here is another (more modern) article about the same, with the example of "Nerdinner".

+6
10 Oct '10 at 8:05
source share

What do you mean by injection? Do you want to apply the principle of dependency inversion on it? If so, then have you ever assumed that you are replacing your EF context with some other context that adheres to the same contract?

For me, you have to encapsulate the EF context somewhere in the framework, so that every request gets an EF DataContext. Apply DI in your repository. Later, your repositories may have different contexts, and you can switch between repositories.

+1
Oct 10 '10 at 7:27
source share



All Articles