我正在尝试利用简单注射器中的一些不错的功能。
我目前在装饰器方面遇到问题,当我期望它们时,它们也没有受到打击。
我正在像这样注册它们:
container.RegisterManyForOpenGeneric(
typeof(ICommandHandler<>),
AppDomain.CurrentDomain.GetAssemblies());
container.RegisterDecorator(
typeof(ICommandHandler<>),
typeof(CreateValidFriendlyUrlCommandHandler<>),
context => context.ServiceType == typeof(ICommandHandler<CreateProductCommand>)
);
container.RegisterDecorator(
typeof(ICommandHandler<>),
typeof(CreateProductValidationCommandHandler<>),
context => context.ServiceType == typeof(ICommandHandler<CreateProductCommand>)
);
我想我一定错过了一些东西,因为我期望调用ICommandHandler<CreateProductCommand>
将在CreateValidFriendlyUrlCommandHandler<>
运行CreateProductValidationCommandHandler<>
之前调用。
我尝试过这样的不同注册:
container.RegisterManyForOpenGeneric(
typeof(ICommandHandler<>),
AppDomain.CurrentDomain.GetAssemblies());
container.RegisterDecorator(
typeof(ICommandHandler<>),
typeof(CreateValidFriendlyUrlCommandHandler<>),
context => context.ImplementationType == typeof(CreateProductCommandHandler)
);
container.RegisterDecorator(
typeof(ICommandHandler<>),
typeof(CreateProductValidationCommandHandler<>),
context => context.ImplementationType == typeof(CreateProductCommandHandler)
);
正如我所想的那样,当and实现可能会遇到一些循环引用时ICommandHandler<CreateProductCommand>
,为类型注册一个装饰器。ICommandHandler<CreateProductCommand>
CreateProductValidationCommandHandler
CreateValidFriendlyUrlCommandHandler
ICommandHandler<CreateProductCommand>
但改变这一点并没有什么不同。
这是我的CreateProductValidationCommandHandler<TCommand>
:
public class CreateProductValidationCommandHandler<TCommand>
: ICommandHandler<CreateProductCommand>
{
private readonly ICommandHandler<TCommand> decorated;
private readonly IValidationService validationService;
public CreateProductValidationCommandHandler(
ICommandHandler<TCommand> decorated,
IValidationService validationService)
{
this.decorated = decorated;
this.validationService = validationService;
}
public void Handle(CreateProductCommand command)
{
if (!validationService.IsValidFriendlyName(
command.Product.ProductFriendlyUrl))
{
command.ModelStateDictionary.AddModelError(
"ProductFriendlyUrl",
"The Friendly Product Name is not valid...");
return;
}
if (!validationService.IsUniqueFriendlyName(
command.Product.ProductFriendlyUrl))
{
command.ModelStateDictionary.AddModelError(
"ProductFriendlyUrl",
"The Friendly Product Name is ...");
return;
}
}
}
这是我的CreateValidFriendlyUrlCommandHandler<TCommand>
:
public class CreateValidFriendlyUrlCommandHandler<TCommand>
: ICommandHandler<CreateProductCommand>
{
private readonly ICommandHandler<TCommand> decorated;
public CreateValidFriendlyUrlCommandHandler(ICommandHandler<TCommand> decorated)
{
this.decorated = decorated;
}
public void Handle(CreateProductCommand command)
{
if (string.IsNullOrWhiteSpace(
command.Product.ProductFriendlyUrl))
{
command.Product.ProductFriendlyUrl =
MakeFriendlyUrl(command.Product.Name);
}
}
}