Daryl Van Sittert
Daryl Van Sittert

Reputation: 877

Structuremap injecting same property instance into collection

I am trying to populate an array of objects that inherit from IFoo. The problem I am facing is that structure map is populating the property within IFoo with the same instance of IBar. I cannot add AlwaysUnique() to IBar because this is used elsewhere in our enterprise application and would have consequences.

Is there anyway that I can get it to create new instances of the Bar object for every Foo in the collection?

public interface IFoo
{
    IBar bar { get; set; }
}

public class Foo1 : IFoo
{
    public IBar bar { get; set; }
    public Foo1(IBar bar) { this.bar = bar; }
}

public class Foo2 : IFoo
{
    public IBar bar { get; set; }
    public Foo2(IBar bar) { this.bar = bar; }
}


public interface IBar
{
    Guid id { get; set; }
}

public class Bar : IBar
{
    public Guid id { get; set; }
    public Bar() {this.id = Guid.NewGuid();}
}


class Program
{
    static void Main(string[] args)
    {
        var container = new Container(_ =>
        {
            _.Scan(x =>
            {
                x.TheCallingAssembly();
                x.AddAllTypesOf<IFoo>();
            });
            _.For<IBar>().Use<Bar>(); //I can't change this line because Bar is used elsewhere in the project
        });

        var foos = container.GetAllInstances<IFoo>();

        if (foos.ElementAt(0).bar == foos.ElementAt(1).bar)
            throw new Exception("Bar must be a different instance");
    }
}

Upvotes: 0

Views: 71

Answers (1)

Stuart Grassie
Stuart Grassie

Reputation: 3073

You could do this with a custom policy. See example 3 here, you could adapt that to your needs.

Something like:

public class BarUniqueForFoo : IInstancePolicy
{
    public void Apply(Type pluginType, Instance instance)
    {
        if (pluginType == typeof(IBar) && instance.ReturnedType == typeof(Bar)
        {
            instance.SetLifecycleTo<UniquePerRequestLifecycle>();
        }
    }
}

Upvotes: 1

Related Questions