简单注入器:条件装饰器中的循环依赖性错误

时间:2016-09-27 22:16:54

标签: c# dependency-injection decorator simple-injector

在重构时,我试图将大量功能从我的基本存储库移动到一些装饰器。由于某种原因,我得到一个循环依赖错误。完整的错误在这里:

  

配置无效。为类型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存在依赖性问题(最终是这种情况)。

如果您还有其他需要,请告诉我。

1 个答案:

答案 0 :(得分:1)

我通过添加检查来修复它,以确保我没有将装饰器注入其自身。这是怎么做的?

// 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);