Dmitrii
Dmitrii

Reputation: 1257

Dependencies registration in Application_BeginRequest() method

Is this normal to write the following code:

protected void Application_BeginRequest()
{
    var container = new UnityContainer()
        .RegisterType<IUnitOfWork, MyEntities>()

    HttpContext.Current.Items["container"] = container;

    ServiceLocator.SetLocatorProvider(
        () => new UnityServiceLocator(container));
}

protected void Application_EndRequest()
{
    var container = HttpContext.Current.Items["container"] 
        as UnityContainer;

    if (container != null)
    {
        container.Dispose();
    }
}

Or registering dependencies for every request is a bad practice?

Thanks.

Upvotes: 3

Views: 727

Answers (1)

Steven
Steven

Reputation: 172646

Note: the following advice holds for all IoC frameworks and is not specific to Unity.

TLDR: don't do this. Register the container once in Application_Start and call ServiceLocator.SetLocatorProvider just once.

It is fine to register dependencies to have a 'per request' or 'per web request' lifetime. Creating a new container instance per web request however, is a very bad practice.

Containers are optimized for resolving instances (not for registering), which often means there is some dynamic code generation going on under the covers when a type is requested (from the container) for the first time. The registration and code generation and compilation process can be pretty time consuming, and creating a new instance of the container on each web request, will trigger the complete registration and code generation process all over again. This takes time, generates many temporary objects (more garbage to be collected), and generates new code that must be cached at least during the lifetime of that container instance.

Further more, having multiple container instances, makes it hard to do other optimizations, such as registering instances with a bigger scope than per web request. In your case, registering a type as 'singleton' practically means 'per web request', since that type is singleton within the context of that container instance. Or even without performance as a consideration, for some types to work correctly, you'll need a lifetime larger than 'per web request' (such as one instance per app domain), which is harder to configure.

You probably can do this, even with a container per request, but your code will be much harder to maintain.

The container itself is thread-safe, so there is in that sense no need to have container instance per request.

And in your case it is even worse, since you have a race condition, a concurrency bug, in your code, since you change the ServiceLocator on each request. The ServiceLocator stores the registered delegate in a private static field, which means it is accessible from all threads. In other words, you are sharing container instances over web requests. You probably won't notice during development, since you will be having one web request at the time, but when you have code calling ServiceLocator.Current, it will fail in production. Take for instance the following very likely scenario where request 1 starts and sets the service locator. After that, request 2 starts and overrides the service locator with it's own container instance. After that, code in request 1 calls ServiceLocator.Current which now returns the container of the second request. Sometimes (if you're lucky) you'll get an ObjectDisposedException. This will happen if a thread disposes its container that another thread is still (incorrectly) using. Sometimes however, types are resolved that belong to a different web request (instances that are unsafe to be used over multiple threads), which is obviously bad and causes all kinds of strange and incorrect behavior. For instance when you return a LINQ to SQL DataContext or Entity Framework ObjectContext instance. Those classes should normally be configured per web request and can't be shared by multiple threads.

Upvotes: 5

Related Questions