在构造函数中获取Y类型的X实例

时间:2016-02-16 06:07:22

标签: c# autofac

如果我在以下代码中使用AutoFac设置我的依赖项,我如何确保objects.ToList()返回包含X个元素的列表?

public interface IClassA { ... }
public class ClassA : IClassA { ... }

public interface IClassB { ... }
public class ClassB : IClassB
{
    public ClassB(IEnumerable<IClassA> objects)
    {
    }
}

当前容器构建代码(请注意,这与TopShelf一起使用):

public static class DependencyContainer
{
    public static IContainer BuildContainer()
    {
        var builder = new ContainerBuilder();

        builder.RegisterType<ClassA>().As<IClassA>();
        builder.RegisterType<ClassB>().As<IClassB>().SingleInstance();

        return builder.Build();
    }
}

1 个答案:

答案 0 :(得分:2)

如果将以下内容添加到DependencyContainer类中,则可以指出应将哪些实例注入ClassB构造函数:

    builder.Register(c => 
                return new [] { c.Resolve<IClassA>(), c.Resolve<IClassA>() })
           .As<IEnumerable<IClassA>>();

所以:

public static class DependencyContainer
{
    public static IContainer BuildContainer()
    {
        var builder = new ContainerBuilder();

        builder.RegisterType<ClassA>().As<IClassA>();
        builder.RegisterType<ClassB>().As<IClassB>().SingleInstance();

        builder.Register(c => 
            return new [] { c.Resolve<IClassA>(), c.Resolve<IClassA>() })
               .As<IEnumerable<IClassA>>();

        return builder.Build();
    }
}

如果您想在运行时动态创建数字,可以将以下内容添加到DependencyContainer类:

public static IEnumerable<IClassA> CreateInstances(IComponentContext component)
{
    const int number = 3; // <-- YOU COULD READ THIS FROM A CONFIG FILE
    List<IClassA> instances = new List<IClassA>();

    for(int i = 0; i < number; i++)
    {
        instances.Add(component.Resolve<IClassA>());
    }

    return instances;
}

然后将Register(c => return new [] { ... })替换为:

builder.Register(c => CreateInstances(c)).As<IEnumerable<IClassA>>();