Autofac 設置方法攔截器的兩種方式


前提

1.Nuget安裝Autofac 4.0以下版本  4.0及4.0 以上版本暫時沒找到合適的方案

2.Nuget安裝Autofac.Extras.DynamicProxy2

3.創建一個類似下面代碼得 攔截類

    public class TestInterceptor : IInterceptor
    {
        public void Intercept(IInvocation invocation)
        {
            string c = string.Format("Calling method {0} with parameters {1}... ",
     invocation.Method.Name,
     string.Join(", ", invocation.Arguments.Select(a => (a ?? "").ToString()).ToArray()));

            invocation.Proceed();

            string b = string.Format("Done: result was {0}.", invocation.ReturnValue);
        }
    }

注:autufac文檔

http://docs.autofac.org/en/latest/advanced/interceptors.html

第一種方式

在接口或者實現類添加[Intercept(typeof(TestInterceptor))]標簽

如:

   [Intercept(typeof(TestInterceptor))]
    public interface IPersonRepository
    {
        IEnumerable<Person> GetAll();
        Person Get(int id);
        Person Add(Person item);
        bool Update(Person item);
        bool Delete(int id);
    }

添加注入代碼的時候這樣寫:

builder.RegisterType<PersonRepository>().EnableInterfaceInterceptors().As<IPersonRepository>();

builder.RegisterType<TestInterceptor>();

第二種 

不用添加[Intercept(typeof(TestInterceptor))]標簽

添加注入代碼的時候這樣寫:

builder
.RegisterType<PersonRepository>()
.EnableInterfaceInterceptors()
.InterceptedBy(typeof(TestInterceptor))
.As<IPersonRepository>();

好了  結束

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM