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を受け取るオーバーロードを使用し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 に答える