Skip to content

IoC integration: Unity

hazzik edited this page May 28, 2012 · 2 revisions

Back to Home

First off, install MvcExtensions.Unity from nuget:

PM> Install-Package MvcExtensions.Unity

Second you need to inherit you MvcApplication class located in Global.asax.cs from MvcExtensions.Unity.UnityMvcApplication base class.

//Global.asax.cs
public class MvcApplication : MvcExtensions.Unity.UnityMvcApplication
{
}

Third you want to register controller handling by Unity IoC container. For that just include RegisterControllers task into bootstrapper tasks executing sequence:

//Global.asax.cs
public class MvcApplication : MvcExtensions.Unity.UnityMvcApplication
{
	public MvcApplication()
	{
		Bootstrapper.BootstrapperTasks
			.Include<RegisterControllers>();
	}
}

Next you should write Unity's modules to register your components (Please see how to register your services in modules at http://msdn.microsoft.com/en-us/library/ff921149(v=pandp.20).aspx). Place them somewhere in your application folder (for ex. into /Infrastructure) and it will be picked up automatically. Note that you shouldn't install your controllers by that way, because it is already installed by framework.

public class RepositoryModule : IModule
{
	 public void Install(IWindsorContainer container, IConfigurationStore store)
	 {
		  container.RegisterType<IDatabase, InMemoryDatabase>(new PerRequestLifetimeManager());
                  container.RegisterType(typeof(IRepository<>), typeof(Repository<>), new PerRequestLifetimeManager());
		  // ...
	 }
}

Back to Home