StructureMap和命名实例

时间:2010-07-06 23:05:34

标签: .net dependency-injection structuremap

我不确定以下为什么不起作用。 StructureMap告诉我没有为SomeClassWithDependencies ... um ...依赖项定义默认依赖项。任何人都可以对此有所了解吗?我想基于命名实例通过整个依赖树构造对象。我吠叫错了树吗?

public class Program
{
    static void Main(string[] args)
    {
        ObjectFactory.Initialize(x=>x.AddRegistry(new MyRegistry()));


        ISomeClassWithDependencies someClassWithDependencies = ObjectFactory.GetNamedInstance<ISomeClassWithDependencies>("name1");
    }
}
public interface ISomeClassWithDependencies
{
}

public class SomeClassWithDependencies : ISomeClassWithDependencies
{
    public IEnumerable<IValidator> Validators { get; private set; }

    public SomeClassWithDependencies(IEnumerable<IValidator> type1s)
    {
        Validators = type1s;
    }
}

public class MyRegistry : Registry
{
    public MyRegistry()
    {
        ForRequestedType<ISomeClassWithDependencies>().AddInstances(
            x => x.Is.OfConcreteType<SomeClassWithDependencies>().WithName("name1"));
        ForRequestedType<IEnumerable<IValidator>>().AddInstances(x=>x.ConstructedBy(BuildValidators).WithName("name1"));
        ForRequestedType<IEnumerable<IValidator>>().AddInstances(x => x.ConstructedBy(BuildValidators2).WithName("name2"));
    }

    public IEnumerable<IValidator> BuildValidators()
    {
        var validatorOne = ObjectFactory.GetInstance<Validator1>();
        var validatorTwo = ObjectFactory.GetInstance<Validator2>();

        return new List<IValidator> { validatorOne, validatorTwo };
    }

    public IEnumerable<IValidator> BuildValidators2()
    {
        var validatorOne = ObjectFactory.GetInstance<Validator1>();

        return new List<IValidator> { validatorOne };
    }
}

1 个答案:

答案 0 :(得分:1)

首先,您已将两个不同的实例命名为“name1”,其次IEnumerables,数组和IList/List<T>由StructureMap专门处理,并且例如Ctor<IEnumerable<T>>()的调用被忽略。

您可以在注册表中使用(仅)这个(2.6.1语法):

For<ISomeClassWithDependencies>().Use<SomeClassWithDependencies>()
            .EnumerableOf<IValidator>("type1s").Contains(
            x =>
                {
                    x.Type<Validator1>();
                    x.Type<Validator2>();
                }
            );

使用

创建实例
var someClassWithDependencies =
            ObjectFactory.GetInstance<ISomeClassWithDependencies>();