使用装饰模式与统一容器(单身人士)

时间:2017-05-17 07:47:24

标签: c# dependency-injection unity-container

我有2个接口,一个继承自另一个接口。 对于基本接口,我有一个单例实现,对于子接口,我有一个装饰器单例实现(装饰基础实现)

现在,如果将基本接口注入(或解析)到其他客户端,它们将获得基本实现,而不是装饰器(如果它们依赖于子接口,它们只获取装饰器)

我想要的是,装饰器实现应该注入到每个客户端,但是仍然需要构造基本实现并将其注入装饰器单例。

如何设置?

using System;
using Microsoft.Practices.Unity;

public interface IProvider
{
    int GetValue();
}

public interface ITracker : IProvider
{       
}

public class Provider : IProvider
{
    public int GetValue()
    {
         Console.WriteLine("provider");
         return 0;
    }
}

跟踪器:

public class Tracker : ITracker
{
    private readonly IProvider provider;

    public Tracker(IProvider provider)
    {
         this.provider = provider;
    }

    public int GetValue()
    {
        Console.WriteLine("tracker");
        return provider.GetValue();
    }
}

程序:

class Program
{
    static void Main(string[] args)
    {
        var container = new UnityContainer();

        container.RegisterType<IProvider, Provider>(
            new ContainerControlledLifetimeManager());
        container.RegisterType<ITracker, Tracker>(
            new ContainerControlledLifetimeManager());

        // want to get Tracker singleton instance here 
        var provider = container.Resolve<IProvider>(); 

        // want to get Tracker singleton instance here
        var tracker = container.Resolve<ITracker>(); 
    }
}

1 个答案:

答案 0 :(得分:0)

我不是Unity的专家,但这就是我的目标:

由于Tracker是单例,您可以将IProvider作为构造函数参数传递。然后你设置IProvider&amp; ITracker将解析为Tracker的实例。虽然我仍然需要将IProvder投射到ITracker。

var container = new UnityContainer();
container.RegisterType<IDependency, Dependency>();   
container.RegisterType<IProvider, Provider>("Provider");


container.RegisterType<ITracker, Tracker>
(
    new ContainerControlledLifetimeManager(),
      new InjectionConstructor(
        new ResolvedParameter<IProvider>("Provider")
));

container.RegisterType<IProvider, Tracker>
(
    new ContainerControlledLifetimeManager(),
      new InjectionConstructor(
        new ResolvedParameter<IProvider>("Provider")
));

var p = container.Resolve<IProvider>() as ITracker;
var t = container.Resolve<ITracker>();