Autofac使用Castle.DynamicProxy实现AOP

根据官网的文档写了一些测试代码.分享给大家.

首先使用nuget安装.在包管理器中搜索Autofac.Extras.DynamicProxy2并安装就好了.
第一种方式.直接在接口中指定类型.
下面是代码.
接口:

[Intercept(typeof(CallLog))]
public interface ICategoryService  
{
    List<string> GetCategoryList();
    Task<List<string>> GetCategoryListAsync();
}

实现类:

public class CategoryService : ICategoryService
{
    public  void Insert(CategoryInfo model, int userid = 0)
    {
        Console.WriteLine("service Insert {0}", model); 
    }
}  

AOP拦截实现部分:

public class CallLog : IInterceptor
{
    public void Intercept(IInvocation invocation)
    {
        string name = invocation.Method.Name;
        var mappedParameters = MapParameters(invocation.Arguments, invocation.Method.GetParameters())
        .ToDictionary(x => x.Key, x => x.Value.ToString());
        string parameters = JsonConvert.SerializeObject(mappedParameters);

        Console.WriteLine("before call {0}", name);
        Console.WriteLine("parameters:{0}", parameters);
        invocation.Proceed();
        string returnValue = JsonConvert.SerializeObject(invocation.ReturnValue);

        Console.WriteLine("after call.returnValue:{0}", returnValue);
    }
    public IEnumerable<KeyValuePair<string, object>> MapParameters(object[] arguments, ParameterInfo[] getParameters)
    {
        for (int i = 0; i < arguments.Length; i++)
        {
            yield return new KeyValuePair<string, object>(getParameters[i].Name, arguments[i]);
        }
    }
}  

注入部分:

class Program
{
    static void Main(string[] args)
    {

        var builder = new ContainerBuilder();

        // builder.RegisterType<>
        builder.RegisterType<CategoryService>().As<ICategoryService>() 
            .EnableInterfaceInterceptors()
            .InstancePerLifetimeScope();

        builder.RegisterType<CallLog>().InstancePerLifetimeScope();
        var container = builder.Build();

        ICategoryService service = (ICategoryService)container.Resolve(typeof(ICategoryService));
        CategoryInfo info = new CategoryInfo() { id = 1, name = "ergerg" };
        service.Insert(info);
        Console.ReadLine();
    }


}  

第二种.使用InterceptedBy扩展方法实现.
代码部分:

public class AopTest
{
    private string str { get; set; }
    public AopTest(string s)
    {
        str = s;
    }
    public virtual string GetStr()
    {
        return str;
    }
}  

注入:

 builder.RegisterType<AopTest>()
            .AsSelf()
            .EnableClassInterceptors()
            .InterceptedBy(typeof(CallLog)) 
            .InstancePerLifetimeScope();  

怎么样.简单吧~~~

发表评论

电子邮件地址不会被公开。 必填项已用*标注