ASP.NET Core 整合Autofac和Castle實現自動AOP攔截


前言:

除了ASP.NETCore自帶的IOC容器外,我們還可以使用其他成熟的DI框架,如Autofac,StructureMap等(筆者只用過Unity,Ninject和Castle)。

1.ASP.NET Core中的Autofac

首先在Project.jsonDependency節點為中添加如下引用:

 "Microsoft.Extensions.DependencyInjection": "1.0.0",
 "Autofac": "4.1.1",
 "Autofac.Extensions.DependencyInjection": "4.0.0",

接着我們也修改Startup文件中的ConfigureServices方法,為了接管默認的DI,我們要為函數添加返回值AutofacServiceProvider;

1.1 ConfigureServices函數

public IServiceProvider ConfigureServices(IServiceCollection services)
{
     services.AddApplicationInsightsTelemetry(Configuration);
     services.AddMvc();
     return RegisterAutofac(services);
}

1.2 RegisterAutofac函數

private IServiceProvider RegisterAutofac(IServiceCollection services)
{
     var builder = new ContainerBuilder();
     builder.Populate(services);
     var assembly = this.GetType().GetTypeInfo().Assembly;
     builder.RegisterType<AopInterceptor>();
     builder.RegisterAssemblyTypes(assembly)
                  .Where(type =>
                   typeof(IDependency).IsAssignableFrom(type) && !type.GetTypeInfo().IsAbstract)
                  .AsImplementedInterfaces()
                  .InstancePerLifetimeScope().EnableInterfaceInterceptors().InterceptedBy(typeof(AopInterceptor));
      this.ApplicationContainer = builder.Build();
      return new AutofacServiceProvider(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地址如下:

https://github.com/maxzhang1985/AutofacCastle.AspNetCore.Demo

3.注意事項

(1).創建Autofac容器時不要忘了將ConfigureServices的返回值修改為IServiceProvider。
(2).對應ASP.NET Core提及的不同的生命周期,Autofac也定義了對應的擴展方法,如InstancePerLifetimeScope等,默認為Transient模式,包括EntityFramwork等Context也是該種模式。
(3).Autofac Core不支持從View中注入,但是可以和ASP.NET Core自帶IOC容器配合使用。

 

 

GitHub:https://github.com/maxzhang1985/YOYOFx  如果覺還可以請Star下, 歡迎一起交流。

 

.NET Core 和 YOYOFx 的交流群: 214741894  

 

如果你覺得本文對你有幫助,請點擊“推薦”,謝謝.

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM