结构图将相同的 属性 实例注入集合

Structuremap injecting same property instance into collection

我正在尝试填充从 IFoo 继承的对象数组。我面临的问题是结构映射正在使用 IBar 的相同实例填充 IFoo 中的 属性。我不能将 AlwaysUnique() 添加到 IBar,因为这在我们的企业应用程序的其他地方使用并且会产生后果。

我是否可以使用它为集合中的每个 Foo 创建 Bar 对象的新实例?

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

您可以使用自定义策略执行此操作。请参阅示例 3 here,您可以根据需要对其进行调整。

类似于:

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