Autofac类型在带键的枚举上注册,构造函数未解析

时间:2014-07-28 14:55:51

标签: c# inversion-of-control autofac

目前我们有一个容器注册类型:

var builder = new ContainerBuilder();
builder.RegisterType<FirstClass>().Keyed<IClass>(EnumType.First);
builder.RegisterType<SecondClass>().Keyed<IClass>(EnumType.Second);
...

当我们用默认构造函数(没有构造函数)解决这个问题时,它完美地运行。

传递IIndex的包装器构造函数:

public SomeWrapperClass(ISomeRepo repo, IIndex<EnumType, IClass> classTypes)
    {
        _repo = repo;
        _classTypes = classTypes;
    }

然后我们用这样的方法解决它:

private object DoSomething(EnumType enumType, SomeParameter someParameter)
    {
        var resolvedItem = _extractTypes[enumType];
        return resolvedItem .GenerateExtract(someParameter);
    }

但是如果我们在IClass类型中添加一个带有参数的构造函数就无法找到它,我们尝试以多种方式强制它,包括在构建容器时使用with参数和构造函数关键字。

我们添加的构造函数看起来像这样:

public class ClassImplementation: IClass
{
    private readonly IAnotherClassInterface _dependency;

    public ClassImplementation(IAnotherClassInterface secondClass)
    {
        _dependency = secondClass;
    }
}

我们是在做错事还是不应该这样做?

2 个答案:

答案 0 :(得分:2)

这是一个Visual Studio问题,项目已经建成,但它有一个参考问题。重新启动re-sharper和visual studio后,我们添加了缺少的dll,并使用with constructor关键字解析了类型:

builder.RegisterType<ClassImplementation>()
                .UsingConstructor(typeof (IAnotherClassInterface ))
                .Keyed<IClass>(EnumType.First);

答案 1 :(得分:1)

我不是专家,我还没有对此进行过测试,但是你在黑暗中尝试了一下:

builder.Register(c => new SecondClass(c.Resolve<IDependency>()).Keyed<IClass>(EnumType.Second);

这假定IDependency是可解析的。