Unity - 如何有条件地创建子范围?

时间:2017-11-23 17:27:16

标签: c# unity-container

如果我有:

container.RegisterType<ICalculationBuilder, CalculationBuilder>();

我知道每次解析ICalculationBuilder时都会得到一个新实例。

我知道如果这样做:

var childContainer = container.CreateChildContainer();

childContainer.RegisterType<ICalculationBuilder, CalculationBuilder>(new HierarchicalLifetimeManager());

然后,每次在该子范围内解析ICalculationBuilder时,我都会获得相同的实例。

但是给出了:

class CalculationBuilder
{
  CalculationBuilder(int year)
  {
  }
} 

如何为每年获得一个不同的CalculationBuilder实例?所以,如果我这样做:

var builder1 = childContainer.Resolve(typeof(ICalculationBuilder), new DependencyOverride<int>(2017));

var builder2 = childContainer.Resolve(typeof(ICalculationBuilder), new DependencyOverride<int>(2017));

var builder3 = childContainer.Resolve(typeof(ICalculationBuilder), new DependencyOverride<int>(2018));

然后

Assert.Same(builder1, builder2) would be true

Assert.NotSame(builder2, builder3) would be false

1 个答案:

答案 0 :(得分:1)

我认为,您可以创建某种工厂来管理您的对象:

class CalculationFactory : IDisposable
{
    private readonly Dictionary<int, CalculationBuilder> cache = new Dictionary<int, CalculationBuilder>();
    private readonly IUnityContainer container;

    public ICalculationBuilder Get(int year)
    {
        if (!cache.ContainsKey(year))
        {
            cache[year] = container.Resolve(typeof(ICalculationBuilder), new DependencyOverride<int>(year));
        }

        return cache[year];
    }

    public void Dispose()
    {
        cache.Clear();
    }
}

仅通过此类创建对象。它会缓解每年的失误。