3

如何在中注册条件装饰SimpleInjector?这是我的定义:

public interface ICommand { }

public interface ICleanableCommand : ICommand {
    void Clean();
}

public interface ICommandHandler<in TCommand> 
    where TCommand : ICommand {
    void Handle(TCommand command);
}

public class CleanableCommandHandlerDecorator<TCommand> 
    : ICommandHandler<TCommand> 
    where TCommand : ICleanableCommand {

    private readonly ICommandHandler<TCommand> _handler;

    public CleanableCommandHandlerDecorator(
        ICommandHandler<TCommand> handler) {
        _handler = handler;
    }

    void ICommandHandler<TCommand>.Handle(TCommand command) {
        command.Clean();
        _handler.Handle(command);
    }
}

我正在尝试:

container.RegisterManyForOpenGeneric(
    typeof(ICommandHandler<>),
    AppDomain.CurrentDomain.GetAssemblies()
    );

container.RegisterDecorator(
    typeof(ICommandHandler<>),
    typeof(CleanableCommandHandlerDecorator<>)
    // ,context => context.ImplementationType ???
    // I want to register this decorator for commandhandlers 
    // which their command implements ICleanableCommand 
    );
4

2 回答 2

5

您可以使用RegisterDecorator带 an 的重载DecoratorPredicateContext来定义应应用装饰器的条件。但是,由于在您的情况下,条件只是泛型类型约束,因此您不必提供谓词。当给定的服务类型不可装饰时,Simple Injector 将自动忽略装饰器,这包括泛型类型约束。

换句话说,只需按如下方式注册您的装饰器,它就会正常工作:

container.RegisterDecorator(
    typeof(ICommandHandler<>),
    typeof(CleanableCommandHandlerDecorator<>));
于 2012-10-08T09:43:51.750 回答
2

看来我可以使用DecoratorPredicateContext.ServiceType

container.RegisterDecorator(
    typeof(ICommandHandler<>),
    typeof(CleanableCommandHandlerDecorator<>),
    context => {
        var genArg = context.ServiceType.GetGenericArguments()[0];
        return typeof(ICleanableCommand).IsAssignableFrom(genArg);
    });
于 2012-10-07T01:46:01.903 回答