简体   繁体   中英

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");
    }
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM