什么是AspectCore Project ?
AspectCore Project 是适用于Asp.Net Core 平台的轻量级 Aop(Aspect-oriented programming) 解决方案,它更好的遵循Asp.Net Core的模块化开发理念,使用AspectCore可以更容易构建低耦合、易扩展的Web应用程序。AspectCore使用Emit实现高效的动态代理从而不依赖任何第三方Aop库。
开使使用AspectCore
启动 Visual Studio。从 File 菜单, 选择 New > Project。选择 ASP.NET Core Web Application 项目模版,创建新的 ASP.NET Core Web Application 项目。
从 Nuget 安装 AspectCore.Extensions.DependencyInjection package: PM> Install-Package AspectCore.Extensions.DependencyInjection 在一般情况下可以使用抽象的InterceptorAttribute自定义特性类,它实现IInterceptor接口。AspectCore默认实现了基于Attribute的拦截器配置。我们的自定义拦截器看起来像下面这样:public class CustomInterceptorAttribute : InterceptorAttribute{ public async override Task Invoke(IAspectContext context, AspectDelegate next) { try { Console.WriteLine("Before service call"); await next(context); } catch (Exception) { Console.WriteLine("Service threw an exception!"); throw; } finally { Console.WriteLine("After service call"); } } }
定义ICustomService接口和它的实现类CustomService:
public interface ICustomService{ [CustomInterceptor] void Call();}public class CustomService : ICustomService{ public void Call() { Console.WriteLine("service calling..."); }}
在HomeController中注入ICustomService:
public class HomeController : Controller{ private readonly ICustomService _service; public HomeController(ICustomService service) { _service = service; } public IActionResult Index() { _service.Call(); return View(); }}
注册ICustomService,接着,在ConfigureServices中配置创建代理类型的容器:
public IServiceProvider ConfigureServices(IServiceCollection services){ services.AddTransient<ICustomService, CustomService>(); services.AddMvc(); services.AddAspectCore(); return services.BuildAspectCoreServiceProvider();}
拦截器配置。首先安装AspectCore.Extensions.Configuration package:
PM> Install-Package AspectCore.Extensions.Configuration
全局拦截器。使用AddAspectCore(Action<AspectCoreOptions>)
的重载方法,其中AspectCoreOptions提供InterceptorFactories注册全局拦截器:
services.AddAspectCore(config => { config.InterceptorFactories.AddTyped<CustomInterceptorAttribute>(); });
带构造器参数的全局拦截器,在CustomInterceptorAttribute
中添加带参数的构造器:
public class CustomInterceptorAttribute : InterceptorAttribute{ private readonly string _name; public CustomInterceptorAttribute(string name) { _name = name; } public async override Task Invoke(AspectContext context, AspectDelegate next) { try { Console.WriteLine("Before service call"); await next(context); } catch (Exception) { Console.WriteLine("Service threw an exception!"); throw; } finally { Console.WriteLine("After service call"); } }}
新闻热点
疑难解答
图片精选