Share via


Adding Unity to Your Web Applications

patterns & practices Developer Center

Download codeDownload PDFOrder Paperback

If you are using Unity in an ASP.NET MVC application, you should add the Unity bootstrapper for ASP.NET MVC NuGet package to your project. This package adds code to your application to automatically register your MVC controllers in the Unity container and enables you to inject dependencies into the controllers. This package also adds support for the PerRequestLifetimeManager to the application. For more information, see the comments in the UnityConfig.cs and UnityMvcActivator.cs source files that the package adds to the App_Start folder in your project.

Note

You must add the Unity bootstrapper for ASP.NET MVC NuGet package to your web application project to use the PerRequestLifetimeManager.

Although the PerRequestLifetimeManager lifetime manager class works correctly and can help you to work with stateful or thread-unsafe dependencies within the scope of an HTTP request, it is generally not a good idea to use it when you can avoid it. Using this lifetime manager can often lead to bad practices or hard to find bugs in the end user’s application code when used incorrectly. It is recommended that the dependencies you register with the Unity container are stateless, and if you have a requirement to share common state between several objects during the lifetime of an HTTP request, then you can have a stateless service that explicitly stores and retrieves this state using the System.Web.HttpContext.Items collection of the System.Web.HttpContext.Current object.

If you use the PerRequestLifetimeManager lifetime manager class, then to ensure that the instance of the registered type is disposed automatically when the HTTP request completes, make sure to register the UnityPerRequestHttpModule with the web application. To do this, invoke the following code in the Unity bootstrapping class (typically in the file UnityMvcActivator.cs):

DynamicModuleUtility.RegisterModule(typeof(UnityPerRequestHttpModule));

If you are using Unity in an ASP.NET Web API application, you should add the Unity bootstrapper for ASP.NET WebApi NuGet package to your project to enable dependency injection in the controller classes. For more information, see the comments in the UnityConfig.cs and UnityWebApiActivator.cs source files that the package adds to the App_Start folder in your project.

Note

To use the PerRequestLifetimeManager class in an ASP.NET Web API application, you must also add the the Unity bootstrapper for ASP.NET MVC NuGet package to your project.

You can add both the Unity bootstrapper for ASP.NET MVC and Unity bootstrapper for ASP.NET WebApi NuGet packages to the same project.

Next Topic | Previous Topic | Home | Community