Autofac Interception with custom attributes

I was looking for a specific solution for registering AOP. I need an interception that allows me to do something like this:

[MyCustomLogging("someParameter")]

The fact is, I saw examples in other DI environments that make this possible. But my project already uses Autofac for DI, and I don’t know how good the idea is with Unity (for example). In Autofac.extras.dynamiclibrary2, the InterceptAttribute class is sealed.

Anyone have an idea for this problem?

Ps: I would be pleased with this:

[Intercept(typeof(MyLoggingClass), "anotherParameter"]
+4
source share
1 answer

, .

, , :

  • , . , ​​ , . , Injection Dependency; , .
  • ( , ), , . . , , , . ( - Order), Order. . Open/closed.
  • ( typeof(MyLoggingClass)), . , , . , , . , -, -, Windows. -, -. , .

. , . - , , , , . , . , , SOLID, DRY, .

, SOLID , , , , - , :

public class LoggingCommandHandlerDecorator<T> : ICommandHandler<T>
{
    private readonly ILogger logger;
    private readonly ICommandHandler<T> decoratee;
    public LoggingCommandHandlerDecorator(ILogger logger, ICommandHandler<T> decoratee) {
        this.logger = logger;
        this.decoratee = decoratee;
    }

    public void Handle(T command) {
        this.logger.Log("Handling {0}. Data: {1}", typeof(T).Name,
            JsonConvert.SerializeObject(command));
        this.decoratee.Handle(command);
    }
}

( ), "" , , , ( ). , , , , , , .

node. , . , , . :

[Permission(Permissions.Crm.ManageCompanies)]
public class BlockCompany : ICommand {
    public Guid CompanyId;
}

, , - (PermissionAttribute - , ( ) ) AOP. .

, , , , , , . , :

public class PermissionCommandHandlerDecorator<T> : ICommandHandler<T>
{
    private static readonly Guid requiredPermissionId =
        typeof(T).GetCustomAttribute<PermissionAttribute>().PermissionId;

    private readonly IUserPermissionChecker checker;
    private readonly ICommandHandler<T> decoratee;

    public PermissionCommandHandlerDecorator(IUserPermissionChecker checker,
        ICommandHandler<T> decoratee) {
        this.checker = checker;
        this.decoratee = decoratee;
    }

    public void Handle(T command) {
        this.checker.CheckPermission(requiredPermissionId);
        this.decoratee.Handle(command);
    }
}
+9

Source: https://habr.com/ru/post/1584758/


All Articles