-
Notifications
You must be signed in to change notification settings - Fork 17
IoC Integration: Autofac
First off, install MvcExtensions.Autofac from nuget:
PM> Install-Package MvcExtensions.Autofac
The integration with autofac is similar with other IoC frameworks: you just have to inherit your MvcApplication class located in Global.asax.cs from MvcExtensions.Autofac.AutofacMvcApplication base class.
//Global.asax.cs
public class MvcApplication : MvcExtensions.Autofac.AutofacMvcApplication
{
}
Second you want to register controller handling by Castle.Windsor IoC container. For that just include RegisterControllers task into bootstrapper tasks executing sequence:
//Global.asax.cs
public class MvcApplication : MvcExtensions.Autofac.AutofacMvcApplication
{
public MvcApplication()
{
Bootstrapper.BootstrapperTasks
.Include<RegisterRoutes>() // *
.Include<RegisterControllers>();
}
}
- see more about RegisterRoutes class
Next you should write autofac's modules to register your components (see http://code.google.com/p/autofac/wiki/StructuringWithModules). 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 CarTransportModule : Module
{
public bool ObeySpeedLimit { get; set; }
protected override void Load(ContainerBuilder builder)
{
builder.Register(c => new Car(c.Resolve<IDriver>())).As<IVehicle>();
builder.RegisterType<SaneDriver>().As<IDriver>();
}
}
One more additional thing you have to do is to add an empty autofac's section to the config file:
<configuration>
<configSections>
<section name="autofac" type="Autofac.Configuration.SectionHandler, Autofac.Configuration" />
</configSections>
<autofac />
<!-- ... -->
<configuration>
That it to get started with autofac integration.