Asp.NetCore轻量级Aop解决⽅案:AspectCore
什么是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");
}
}
writeline教程
}
定义ICustomService接⼝和它的实现类CustomService:
public interface ICustomService
{
[CustomInterceptor]
void Call();
}
public class CustomService : ICustomService
{
public void Call()
{
Console.WriteLine("");
}
}
在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");
}
}
}
修改全局注册:
services.AddAspectCore(config =>
{
config.InterceptorFactories.AddTyped<CustomInterceptorAttribute>(args: new object[] { "custom" });
});
作为服务的全局。在ConfigureServices中添加:
services.AddTransient<CustomInterceptorAttribute>(provider => new CustomInterceptorAttribute("service"));
修改全局注册:
services.AddAspectCore(config =>
{
config.InterceptorFactories.AddServiced<CustomInterceptorAttribute>();
});
作⽤于特定Service或Method的全局,下⾯的代码演⽰了作⽤于带有Service后缀的类的全局:
services.AddAspectCore(config =>
{
config.InterceptorFactories.AddTyped<CustomInterceptorAttribute>(method => method.DeclaringType.Name.EndsWith("Service"));
});
使⽤通配符的特定全局:
services.AddAspectCore(config =>
{
config.InterceptorFactories.AddTyped<CustomInterceptorAttribute>(PredicateFactory.ForService("*Service"));
});
在AspectCore中提供NonAspectAttribute来使得Service或Method不被代理:
[NonAspect]
public interface ICustomService
{
void Call();
}
同时⽀持全局忽略配置,亦⽀持通配符:
services.AddAspectCore(config =>
{
//App1命名空间下的Service不会被代理
config.NonAspectOptions.AddNamespace("App1");
//最后⼀级为App1的命名空间下的Service不会被代理
config.NonAspectOptions.AddNamespace("*.App1");
//ICustomService接⼝不会被代理
config.NonAspectOptions.AddService("ICustomService");
//后缀为Service的接⼝和类不会被代理
config.NonAspectOptions.AddService("*Service");
//命名为Query的⽅法不会被代理
config.NonAspectOptions.AddMethod("Query");
//后缀为Query的⽅法不会被代理
config.NonAspectOptions.AddMethod("*Query");
});
中的依赖注⼊。在中⽀持属性注⼊,构造器注⼊和服务定位器模式。
属性注⼊,在中拥有public get and set权限的属性标记[AspectCore.Abstractions.FromServices](区别
于Microsoft.AspNetCore.Mvc.FromServices)特性,即可⾃动注⼊该属性,如:
public class CustomInterceptorAttribute : InterceptorAttribute
{
[AspectCore.Abstractions.FromServices]
public ILogger<CustomInterceptorAttribute> Logger { get; set; }
public override Task Invoke(AspectContext context, AspectDelegate next)
{
Logger.LogInformation("call interceptor");
return next(context);
}
}
构造器注⼊需要使作为Service,除全局外,仍可使⽤ServiceInterceptor使从DI中激活:
public interface ICustomService
{
[ServiceInterceptor(typeof(CustomInterceptorAttribute))]
void Call();
}
服务定位器模式。上下⽂AspectContext可以获取当前Scoped的ServiceProvider:
public class CustomInterceptorAttribute : InterceptorAttribute
{
public override Task Invoke(AspectContext context, AspectDelegate next)
{
var logger = context.ServiceProvider.GetService<ILogger<CustomInterceptorAttribute>>();
logger.LogInformation("call interceptor");
return next(context);
}
}
使⽤Autofac和AspectCore。AspectCore原⽣⽀持集成Autofac,我们需要安装下⾯两个nuget packages:
PM> Install-Package Autofac.Extensions.DependencyInjection
PM> Install-Package AspectCore.Extensions.Autofac
AspectCore提供RegisterAspectCore扩展⽅法在Autofac的Container中注册动态代理需要的服务,并提供AsInterfacesProxy 和AsClassProxy扩展⽅法启⽤interface和class的代理。修改ConfigureServices⽅法为:
public IServiceProvider ConfigureServices(IServiceCollection services)
{
services.AddMvc();
var container = new ContainerBuilder();
container.RegisterAspectCore();
container.Populate(services);
container.RegisterType<CustomService>().As<ICustomService>().InstancePerDependency().AsInterfacesProxy();
return new AutofacServiceProvider(container.Build());
}
有问题反馈
如果您有任何问题,请提交 Issue 给我们。
以上所述是⼩编给⼤家介绍的Asp.Net Core轻量级Aop解决⽅案:AspectCore,希望对⼤家有所帮助,如果⼤家有任何疑问请给我留⾔,⼩编会及时回复⼤家的。在此也⾮常感谢⼤家对⽹站的⽀持!

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。