简体   繁体   中英

How can I “bootstrap” Castle Windsor into my ASP.NET MVC 6 project?

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?

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>();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM