using Microsoft.Extensions.DependencyInjection;
using System;
using AspectCore.Extensions.DependencyInjection;
using AspectCore.DynamicProxy;
using System.Threading.Tasks;
using System.Collections.Generic;
namespace ConsoleApp4
{
class Program
{
static void Main(string[] args)
{
ServiceCollection services = new ServiceCollection();
services.ConfigureDynamicProxy();
services.AddTransient<IMySql, MySql>();
var provider = services.BuildDynamicProxyProvider();
var service = provider.GetService<IMySql>();
service.GetData(10);
service.GetData(10);
Console.Read();
}
}
public class MyLogInterceptorAttribute : AbstractInterceptorAttribute
{
public override Task Invoke(AspectContext context, AspectDelegate next)
{
Console.WriteLine("开始记录日志");
var task = next(context);
Console.WriteLine("结束记录日志");
return task;
}
}
public class MyCacheInterceptorAtrribute : AbstractInterceptorAttribute
{
private Dictionary<string, string> cacheDict = new Dictionary<string, string>();
public override Task Invoke(AspectContext context, AspectDelegate next)
{
var cacheKey = string.Join(",", context.Parameters);
if (cacheDict.ContainsKey(cacheKey))
{
context.ReturnValue = cacheDict[cacheKey].ToString();
return Task.CompletedTask;
}
var task = next(context);
var cacheValue = context.ReturnValue;
cacheDict.Add(cacheKey, string.Format("From cache:{0}", cacheValue.ToString()));
return task;
}
}
public interface IMySql
{
string GetData(int id);
}
public class MySql : IMySql
{
[MyLogInterceptor]
[MyCacheInterceptorAtrribute]
public string GetData(int id)
{
var msg = $"已经获得id={id}的数据";
Console.WriteLine(msg);
return msg;
}
}
}