Two ways to set method interceptors in Autofac

premise

1. No suitable solution has been found for Nuget to install Autofac versions 4.0 and above below 4.0

2. Nuget installs Autofac Extras. DynamicProxy2

3. Create an interception class similar to the following code

     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); } }

Note: autufac document

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

The first way

Add [Intercept (typeof (TestInterceptor))] tag to the interface or implementation class

For example:

 [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); }

When adding injection code, write as follows:

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

Second

Do not add the [Intercept (typeof (TestInterceptor))] tag

When adding injection code, write as follows:

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

Okay, it's over

 

posted on 2016-10-09 12:14   Six desires   Reading( three thousand nine hundred and fifty-three Comments( zero edit   Collection   report

Navigation