【发布时间】:2017-02-05 16:57:21
【问题描述】:
在重构时,我试图将很多功能从我的基础存储库转移到一些装饰器中。出于某种原因,我收到了循环依赖错误。完整的错误在这里:
配置无效。为类型
IValidator<EntityDTO>创建实例失败。配置无效。EntityReaderExcludeDefaultEntitiesDecorator类型直接或间接依赖于自身。
这是我的IValidator 实现(流利验证)
public class EntityValidator : IValidator<EntityDTO>
{
private readonly Data.IEntityReader _repo;
public EntityValidator(Data.IEntityReader repo)
{
_repo = repo;
RuleFor(e => e.GroupId).NotEqual(Guid.Empty)
.WithMessage("The selected group is invalid");
// more rules
}
}
这是我的装饰器实现
public class EntityReaderExcludeDefaultEntitiesDecorator : IEntityReader
{
private readonly IEntityReader _reader;
public EntityReaderExcludeDefaultEntitiesDecorator(IEntityReader reader)
{
_reader = reader;
}
public EntityDTO FindById(Guid id)
{
var entity = _reader.FindById(id);
if (entity.Name.Equals(DocumentConstants.DEFAULT_ENTITY_NAME)) return null;
return entity;
}
// more methods
}
这是我对装饰器的配置
container.RegisterConditional(typeof(IEntityWriter),
typeof(Service.Decorators.EntityWriterValidationDecorator),
context => context.Consumer.ServiceType != typeof(IGroupWriter));
// Do not use the decorator in the Document Writer (We need to find the 'None' entity
container.RegisterConditional(typeof(IEntityReader),
typeof(Service.Decorators.EntityReaderExcludeDefaultEntitiesDecorator),
context => context.Consumer.ServiceType != typeof(IDocumentWriter));
container.RegisterConditional<IEntityWriter, DocumentEntityWriter>(c => !c.Handled);
container.RegisterConditional<IEntityReader, DocumentEntityReader>(c => !c.Handled);
我会提供更多信息,但我不知道这是为什么。我没有正确设置我的装饰器吗?
我没有包含IValidator 注册,因为它是正确的。该错误似乎是在说我们无法实例化 IValidator<EntityDTO> 的原因是因为 EntityReaderExcludeDefaultEntitiesDecorator 存在依赖问题(最终就是这种情况)。
如果你还需要什么,请告诉我。
【问题讨论】:
-
您的问题令人困惑。异常消息涉及
IValidator<EntityDTO>,而您的代码显示AbstractValidator<EntityDTO>,并且您在注册中注册了IEntityReader。我迷路了。 -
@Steven 对不起。我更新了一下。不过,IValidator 注册是正确的。该异常似乎是说装饰器存在问题,这就是我没有包含 IValidator 注册的原因。这似乎与问题无关。
标签: c# dependency-injection decorator simple-injector