所在的位置: Web开发 >> HTNL >> ASPNETCore整合Autofac

ASPNETCore整合Autofac

前言:

除了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地址如下:









































北京那家医院看白癜风最好
中医白癜风知名医院



转载请注明:http://www.guyukameng.com/html/9958.html

  • 上一篇文章:
  •   
  • 下一篇文章: 没有了