gpt4 book ai didi

c# - 如何使用 SimpleInjector 将条件装饰器应用于命令处理程序?

转载 作者:行者123 更新时间:2023-11-30 17:39:42 25 4
gpt4 key购买 nike

我有以下命令处理程序接口(interface):

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

我正在使用以下具体类装饰此接口(interface)的实例:

public class ValidationCommandHandlerDecorator<TCommand> : ICommandHandler<TCommand>
where TCommand : ICommand
{
public ValidationCommandHandlerDecorator(
IValidator<TCommand> validator,
ICommandHandler<TCommand> handler)
{
}

public void Handle(TCommand command) { }
}

但是....我不一定要装饰所有命令处理程序,只想装饰 ICommandHandler<TCommand>如果实例存在/已注册 IValidator<TCommand>对于具体类型的 TCommand。请注意 IValidator<TCommand> instance被注入(inject)到装饰器类的构造函数中。

例如,如果我有一个命令处理程序:

public class CreateFooCommandHandler : ICommandHandler<CreateFooCommand>

如果我注册了以下实例,我只想装饰:

public class CreateFooCommandValidator : IValidator<CreateFooCommand>

如果CreateFooCommandValidator不存在那么我不想装饰 CreateFooCommandHandlerValidationCommandHandlerDecorator .

我在注册 SimpleInjector 时使用了以下内容:

var container = new Container();

container.Register(typeof(ICommandHandler<>), assemblies);
container.Register(typeof(IValidator<>), assemblies);
container.RegisterDecorator(
typeof(ICommandHandler<>),
typeof(ValidationCommandHandlerDecorator<>));

如果没有 IValidator<> 的实例,显然这会失败为任何给定的礼物ICommandHandler<> .咨询assemblies是用于注册通用类的程序集的集合。

如果可能的话,我应该使用什么来注册装饰器/验证器来实现我想做的事情?我不想从使用 SimpleInjector 切换。

此外,如果可能的话,这是推荐的做法还是违反了 SOLID 原则,甚至只是一种代码味道?

最佳答案

您可以通过分析容器中的注册并决定是否装饰每个实例来注册条件装饰器,但我认为这不是最佳选择。最简单的解决方案是为那些实际 IValidator 不存在的实例定义并注册回退 NullValidator ...

public class NullValidator<TCommand> : IValidator<TCommand> where TCommand : ICommand
{
public void Validate(TCommand command)
{
}
}

注册为条件:

var container = new Container();

container.Register(typeof(ICommandHandler<>), assemblies);
container.Register(typeof(IValidator<>), assemblies);
container.RegisterConditional(
typeof(IValidator<>),
typeof(NullValidator<>),
c => !c.Handled);
container.RegisterDecorator(
typeof(ICommandHandler<>),
typeof(ValidationCommandHandlerDecorator<>));

container.Verify();

I don't want to switch from using SimpleInjector.

好人!

Furthermore, if it is possible, is this recommended or is it a violation of SOLID principles, or even just a code smell?

这正是 RegisterConditional 存在的那种东西 :-)

关于c# - 如何使用 SimpleInjector 将条件装饰器应用于命令处理程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35199080/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com