开发者

StructureMap and named instances

开发者 https://www.devze.com 2023-01-06 03:09 出处:网络
I\'m not sure why the following doesn\'t work.StructureMap tells me there is no default dependency defined for SomeClassWithDependencies...um...dependencies.Can anyone shed any light on this?I want to

I'm not sure why the following doesn't work. StructureMap tells me there is no default dependency defined for SomeClassWithDependencies...um...dependencies. Can anyone shed any light on this? I want to construct the object through the entire dependency tree based on the named instances. Am I barking up the wrong tree?

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, validatorT开发者_Python百科wo };
    }

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

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


Firstly you have named two different instances to "name1", secondly IEnumerables, arrays, and IList/List<T>s are treated specially by StructureMap and calls to for example Ctor<IEnumerable<T>>() are ignored.

You could use (only) this in your registry (2.6.1 syntax):

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

and create the instance using

var someClassWithDependencies =
            ObjectFactory.GetInstance<ISomeClassWithDependencies>();
0

精彩评论

暂无评论...
验证码 换一张
取 消