How do I inject dependencies into the global.asax.cs, i.e. the MvcApplication class?
Having previously used the Service Locator (anti-)pattern for dependency injection, I am trying to follow best practice advice in my latest MVC application by using an IOC container (specifically Unity.Mvc3 because it comes with an implementation of the IDependencyResolver out of the box) and constructor injection.
Everything seems quite straight forward so far except for a couple of snags, one of which is in the global.asax.cs (the other is for custom attributes but there's aleady a question on SO covering that).
The HttpApplication event handlers in the MvcApplication class such as:
Application_Start() Application_EndRequest(object sender, EventArgs e) Application_AcquireRequestState(object sender, EventArgs e)
may require external dependencies, e.g. a dependency on an ILogService. So how do I inject them without resorting to the service locator (anti-)pattern of e.g.
private static ILogService LogService { get { return DependencyResolver.Current.GetService<ILogService>(); } }
Any help/advice greatly appreciated!
How to add global. asax file: Select Website >>Add New Item (or Project >> Add New Item if you're using the Visual Studio web project model) and choose the Global Application Class template. After you have added the global.
Global. asax is an optional file which is used to handling higher level application events such as Application_Start, Application_End, Session_Start, Session_End etc. It is also popularly known as ASP.NET Application File. This file resides in the root directory of an ASP. NET-based application.
The class in your global.asax.cs is your Composition Root, so you can't (and shouldn't) inject anything into it from the outside.
However, there's only one instance of the MvcApplication class, so if you need a service in one of its methods, you can just declare it as a member field - e.g:
public class MvcApplication : System.Web.HttpApplication { private readonly ILogService log; public MvcApplication() { this.log = new MyLogService(); } protected void Application_Start() { // ... this.log.Log("Application started"); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With