您的位置:首页 > 编程语言 > ASP

ASP.NET Core 整合Autofac和Castle实现自动AOP拦截

2016-09-29 15:08 721 查看

前言:

除了ASP.NETCore自带的IOC容器外,我们还可以使用其他成熟的DI框架,如Autofac,StructureMap等(笔者只用过Unity,Ninject和Castle)。

1.ASP.NET Core中的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.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

如果你觉得本文对你有帮助,请点击“推荐”,谢谢.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐