除了ASP.NETCore自带的IOC容器外,我们还可以使用其他成熟的DI框架,如Autofac,StructureMap等(笔者只用过Unity,Ninject和Castle)。
1.ASP.NETCore中的Autofac首先在Project.json的Dependency节点为中添加如下引用:
"Microsoft.Extensions.DependencyInjection":"1.0.0",
"Autofac":"4.1.1",
"Autofac.Extensions.DependencyInjection":"4.0.0",
接着我们也修改Startup文件中的ConfigureServices方法,为了接管默认的DI,我们要为函数添加返回值AutofacServiceProvider;
1.1ConfigureServices函数publicIServiceProviderConfigureServices(IServiceCollectionservices)
{
services.AddApplicationInsightsTelemetry(Configuration);
services.AddMvc();
returnRegisterAutofac(services);
}
1.2RegisterAutofac函数privateIServiceProviderRegisterAutofac(IServiceCollectionservices)
{
varbuilder=newContainerBuilder();
builder.Populate(services);
varassembly=this.GetType().GetTypeInfo().Assembly;
builder.RegisterTypeAopInterceptor();
builder.RegisterAssemblyTypes(assembly)
.Where(type=
typeof(IDependency).IsAssignableFrom(type)!type.GetTypeInfo().IsAbstract)
.AsImplementedInterfaces()
.InstancePerLifetimeScope().EnableInterfaceInterceptors().InterceptedBy(typeof(AopInterceptor));
this.ApplicationContainer=builder.Build();
returnnewAutofacServiceProvider(this.ApplicationContainer);
}
这里IDependency接口是一个空接口,为了扫描到实现这个接口的类,自动完成注入操作。
2.整合Castle的DynamicProxy要实现整合,只需要上面函数中,这段代码:
.EnableInterfaceInterceptors().InterceptedBy(typeof(AopInterceptor));
2.2引用程序集显然些程序集还没有Core的对应版本的Autofac.Extras.DynamicProxy,既然说好要整合,就修改一下源代码吧。
Autofac.Extras.DynamicProxy之所以不能支持Core,主要是因为在源码中没有使用新的反射API,GetTypeInfo或使用了一些Remoting的API导致的。
支持Core的Autofac.Extras.DynamicProxy源代码内容和Demo的Github地址如下: