先来个MVC版本的
1:Nuget引入 AspectCore.Extensions.DependencyInjection
2:Startup 类中设置IServiceProvider
public IServiceProvider provider { get; set; }
3:Startup 类ConfigureServices方法注册服务
services.AddScoped<IHuman, Man>();
services.AddDynamicProxy();//注册AOP服务
provider = services.BuildAspectCoreServiceProvider();
4:Startup 类Configure方法,把IServiceProvider写入缓存
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IMemoryCache memoryCache)
{
。。。
memoryCache.Set<IServiceProvider>("provider", provider);
}
5:Controller中调用
public class TestController : Controller
{
IMemoryCache _memoryCache;
public TestController(IMemoryCache memoryCache)
{
_memoryCache = memoryCache;
}
[HttpGet]
public void ManTest()
{
var provider = _memoryCache.Get<IServiceProvider>("provider");
var man = provider.GetService<IHuman>();
man.DoSomeThing();
}
}
6:附上例子中用到的类
public interface IHuman
{
void DoSomeThing();
}
public class Man : IHuman
{
[MyLogInterceptor]
public void DoSomeThing()
{
Console.WriteLine("我是男人,我可以赚很多钱。");
}
}
public class MyLogInterceptorAttribute : AbstractInterceptorAttribute
{
public override Task Invoke(AspectContext context, AspectDelegate next)
{
Console.WriteLine("开始记录日志。。。。。。");
//继续执行
var task = next(context);
Console.WriteLine("结束记录日志。。。。。。");
return task;
}
}
控制台版本的
static void Main(string[] args)
{
//IOC容器
ServiceCollection services = new ServiceCollection();
//注册服务
services.AddDynamicProxy();
services.AddTransient<IMySql, MySql>();
var provider = services.BuildAspectCoreServiceProvider();
var mysql = provider.GetService<IMySql>();
mysql.GetData(10);
Console.Read();
}
public interface IMySql
{
string GetData(int id);
}
public class MySql : IMySql
{
[MyLogInterceptor]
public string GetData(int id)
{
var msg = $"已经获取到数据id={id}的数据";
Console.WriteLine(msg);
return msg;
}
}
public class MyLogInterceptorAttribute : AbstractInterceptorAttribute
{
public override Task Invoke(AspectContext context, AspectDelegate next)
{
Console.WriteLine("开始记录日志。。。。。。");
//继续执行
var task = next(context);
Console.WriteLine("结束记录日志。。。。。。");
return task;
}
}
来源:CSDN
作者:zjc405068789
链接:https://blog.csdn.net/zjc405068789/article/details/104060802