4
votes

I'm trying to use the Castle Windsor IoC container in an ASP.NET MVC 6 project.

I've followed the steps described in the Windsor Tutorial - ASP.NET MVC 3 application up to part 4 where the instructions are:

... we'll be using in the app (the one and only instance), install our installer, and tell MVC infrastructure to use our controller factory instead of its own default. All of that happens in the global.asax file.

Seeing as in MVC 6 Startup.cs replaces global.asax, how should I go about bootstrapping Castle Windsor into my app?

1
@urig see my answer here: stackoverflow.com/questions/28353187/…LeRoi
@Nova tx. If you'd like to post this is a full answer I'll accept it.urig

1 Answers

0
votes

I haven't tried this yet, but it seems the solution is given in the documentation for ASP.NET 5 Dependency Injection under "Replacing the default services container".

The examples there are for AutoFac but the same three steps can be applied to Castle Windsor I believe:

Add the appropriate container package(s) to the dependencies property in project.json.

"dependencies" : {
  "Autofac": "4.0.0-beta8",
  "Autofac.Framework.DependencyInjection": "4.0.0-beta8"
},

Next, in Startup.cs, configure the container in ConfigureServices and change that method to return an IServiceProvider instead of void:

public IServiceProvider ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    // add other framework services

    // Add Autofac
    var containerBuilder = new ContainerBuilder();
    containerBuilder.RegisterModule<DefaultModule>();
    containerBuilder.Populate(services);
    var container = containerBuilder.Build();
    return container.Resolve<IServiceProvider>();
}

Finally, configure Autofac as normal in DefaultModule:

public class DefaultModule : Module
{
    protected override void Load(ContainerBuilder builder)
    {
        builder.RegisterType<CharacterRepository>().As<ICharacterRepository>();
    }
}