This is the 21st day of my participation in Gwen Challenge

This article focuses on the simplest example of integrating Aop functionality using Autofac.

What is the Aop

Create an animal-class interface, a cat class that implements the interface

public interface IAnimal
{
    void Eat();
}
public class Animal:IAnimal
{
    public void Eat()
    {
        Console.WriteLine("吃东西");
    }
}
Copy the code

Create a proxy class. The proxy class implementation executes our own code before and after the Eat interface execution, which is the simplest Aop.

public class CatProxy:IAnimal { private readonly IAnimal _animal; public CatProxy(IAnimal animal) { _animal = animal; } public void Eat() {console. WriteLine(" before eating "); _animal.Eat(); Console.WriteLine(" After eating "); }}Copy the code

How do I implement Aop with AutoFac

In the example above we have implemented a simple static Aop. Is this how we do it when we have 10, 100 classes that need to implement a uniform Aop approach? To monitor the execution time of all controllers, that is to record a time before execution, record the time after execution, two times minus the execution time, such code should be universal. This is where dynamic Aop is needed.

1. Library references

Download via Nuget Autofac. Extras. DynamicProxy, this is a open source library Aufofac implement Aop agency

nuget install  Autofac.Extras.DynamicProxy
Copy the code

Define an Aop interceptor

public class AnimalInterceptor:IInterceptor { public void Intercept(IInvocation invocation) { Console.WriteLine(" Before the animal eats "); invocation.Proceed(); Console.WriteLine(" After the animal has eaten "); }}Copy the code

3. Add a property tag to the class that uses the interceptor

[Intercept(typeof(CatInterceptor))] public class Animal:IAnimal {public void Eat() {Console. }}Copy the code

Autofac injects interceptors

Registration of interceptors is the first step

builder.RegisterType<AnimalInterceptor>(); // Register interceptorsCopy the code

Registered RegisterTypeAninal class and configure interceptor InterceptedBy, finally enable EnableInterfaceInterceptors interceptor

Because the interface is registered to enable the interceptor is EnableInterfaceInterceptors, how is the class registration directly, methods for EnableClassInterceptors

builder.RegisterType<Animal>().As<IAnimal().InterceptedBy(typeof(AnimalInterceptor)).EnableInterfaceInterceptors();
Copy the code

You can also register this way

builder.RegisterType<Animal>().InterceptedBy(typeof(AnimalInterceptor)).EnableClassInterceptors();
Copy the code

5. Test effect

var container = builder.Build();
var animal = container.Resolve<Animal>();
animal.Eat();
Copy the code

reference

.NET implements AOP through Autofac and DynamicProxy

[Autofac- Implementing AOP with Castle.Core (dynamic proxy)](