Following is my implementation for Dependency Injection in MvcApplication class
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
RegisterDependencies();
//pass service into other class that need this service
var c = new OtherClassNeedService(_IYourService);
}
private AutofacDependencyResolver IoCcontainer { get; set; }
private IYourService _IYourService
{
get
{
if (IoCcontainer == null) return null;
return IoCcontainer.ApplicationContainer.Resolve();
}
}
public void RegisterDependencies()
{
var builder = new ContainerBuilder();
builder.RegisterControllers(typeof(MvcApplication).Assembly);
builder.RegisterType()
.As(); //.InstancePerHttpRequest(); if added InstancePerHttpRequest, will get error: No scope with a Tag matching 'httpRequest' is visible from the scope in which the instance was requested.
IContainer container = builder.Build();
var aResolver = new AutofacDependencyResolver(container);
DependencyResolver.SetResolver(aResolver);
IoCcontainer = aResolver;
}
protected void Application_End(object sender, EventArgs e)
{
IoCcontainer.ApplicationContainer.Dispose();
}
}