I need to inject EF context per request. Is there any way to implement it?
What do you mean by injecting? Do you mean to apply dependency inversion principle on it? If yes then do you ever envisage yourself swapping out your EF context with some other context which adheres to same contract?
To me you should encapsulate EF context somewhere in framework, so that every request gets EF DataContext. Apply DI on your repository. Later on your repositories might have different kind of contexts and you can switch repositories with each other.
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.
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();
}