I am trying to understand how Unity IoC works in my Web application. I have created a mvc&api application using visual studio 2015 project template.
Using NuGet i installed Unity. Modified the Unity config to register the types i wanted injected. I had originally added UnityWebActivator.start() to my global.asax file thinking it had to be there in the startup, but when i comment it out, everything still works.
How does the UnityWebActivator get called to configure the new IoC container for unity?
using System.Linq;
using System.Web.Mvc;
using Microsoft.Practices.Unity.Mvc;
[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(WebDirectory.App_Start.UnityWebActivator), "Start")]
[assembly: WebActivatorEx.ApplicationShutdownMethod(typeof(WebDirectory.App_Start.UnityWebActivator), "Shutdown")]
namespace WebDirectory.App_Start
{
/// <summary>Provides the bootstrapping for integrating Unity with ASP.NET MVC.</summary>
public static class UnityWebActivator
{
/// <summary>Integrates Unity when the application starts.</summary>
public static void Start()
{
var container = UnityConfig.GetConfiguredContainer();
FilterProviders.Providers.Remove(FilterProviders.Providers.OfType<FilterAttributeFilterProvider>().First());
FilterProviders.Providers.Add(new UnityFilterAttributeFilterProvider(container));
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
// TODO: Uncomment if you want to use PerRequestLifetimeManager
// Microsoft.Web.Infrastructure.DynamicModuleHelper.DynamicModuleUtility.RegisterModule(typeof(UnityPerRequestHttpModule));
}
/// <summary>Disposes the Unity container when the application is shut down.</summary>
public static void Shutdown()
{
var container = UnityConfig.GetConfiguredContainer();
container.Dispose();
}
}
}
The WebActivatorEx.PreApplicationStartMethod calls the start method early on during application initialization. You'll notice there's also a shutdown method that is called when the application ends.