简单注入器:条件装饰器中的循环依赖错误
本文关键字:循环 依赖 错误 注入器 条件 简单 | 更新日期: 2023-09-27 18:09:03
在重构时,我试图将很多功能从基础存储库移到一些装饰器上。由于某种原因,我得到了一个循环依赖错误。完整的错误在这里:
配置无效。日志含义创建类型为
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
}
}
这是我的Decorator实现
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
有一个依赖问题(最终是这种情况)。
如果您还需要什么,请告诉我。
我通过添加检查来确保我没有将装饰器注入到它本身来修复它。应该这样做吗?
// Do not validate when adding from a group
container.RegisterConditional(typeof(IEntityWriter),
typeof(Decorators.EntityWriterValidationDecorator),
context => context.Consumer.ServiceType != typeof(IGroupWriter)
&& context.Consumer.ImplementationType != context.ImplementationType);
// 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)
&& context.Consumer.ImplementationType != context.ImplementationType);