Autofac 设置方法拦截器的两种方式
生活随笔
收集整理的這篇文章主要介紹了
Autofac 设置方法拦截器的两种方式
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
前提
1.Nuget安裝Autofac 4.0以下版本 ?4.0及4.0 以上版本暫時(shí)沒找到合適的方案
2.Nuget安裝Autofac.Extras.DynamicProxy2
3.創(chuàng)建一個(gè)類似下面代碼得 攔截類
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
第一種方式
在接口或者實(shí)現(xiàn)類添加[Intercept(typeof(TestInterceptor))]標(biāo)簽
如:
[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);}添加注入代碼的時(shí)候這樣寫:
builder.RegisterType<PersonRepository>().EnableInterfaceInterceptors().As<IPersonRepository>();builder.RegisterType<TestInterceptor>();第二種?
不用添加[Intercept(typeof(TestInterceptor))]標(biāo)簽
添加注入代碼的時(shí)候這樣寫:
builder .RegisterType<PersonRepository>() .EnableInterfaceInterceptors() .InterceptedBy(typeof(TestInterceptor)) .As<IPersonRepository>();好了 ?結(jié)束
?
轉(zhuǎn)載于:https://www.cnblogs.com/liuyu7177/p/5941662.html
總結(jié)
以上是生活随笔為你收集整理的Autofac 设置方法拦截器的两种方式的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: PHP基础知识--函数
- 下一篇: Spring 配置解析之Properti