[英]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. 我正在尝试在ASP.NET MVC 6项目中使用Castle Windsor IoC容器。
I've followed the steps described in the Windsor Tutorial - ASP.NET MVC 3 application up to part 4 where the instructions are: 我按照Windsor教程 - ASP.NET MVC 3应用程序中描述的步骤进行了第4部分 ,其中的说明是:
... 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. ...我们将在应用程序中使用(唯一的实例),安装我们的安装程序,并告诉MVC基础架构使用我们的控制器工厂而不是它自己的默认值。 All of that happens in the global.asax file. 所有这些都发生在global.asax文件中。
Seeing as in MVC 6 Startup.cs
replaces global.asax
, how should I go about bootstrapping Castle Windsor into my app? 看到在MVC 6中Startup.cs
取代了global.asax
,我应该如何将Castle Windsor引导到我的应用程序中?
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 ". 我还没有尝试过,但似乎解决方案是在“ 替换默认服务容器 ”下的ASP.NET 5依赖注入文档中给出的。
The examples there are for AutoFac but the same three steps can be applied to Castle Windsor I believe: 有关AutoFac的示例,但相同的三个步骤可应用于Castle Windsor我相信:
Add the appropriate container package(s) to the dependencies property in project.json. 将适当的容器包添加到project.json中的dependencies属性。
"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: 接下来,在Startup.cs中,在ConfigureServices
配置容器并更改该方法以返回IServiceProvider
而不是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: 最后,在DefaultModule中将Autofac配置为正常:
public class DefaultModule : Module
{
protected override void Load(ContainerBuilder builder)
{
builder.RegisterType<CharacterRepository>().As<ICharacterRepository>();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.