views:

33

answers:

1

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, validatorTwo };
    }

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

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

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>();
PHeiberg