如何让 Unity 为 2 个注册接口注入相同的实例

How to make Unity inject the same instance for 2 registered interfaces

我有一个 class (Service),它接收 2 个参数(一个 IClient 和一个 ICounter)。

我希望 Unity 为两者注入 相同的实例 (实现两个接口的 Decorator)。

但是如何呢?

还有一件事:我希望 Unity 使用 每线程基础 将相同的实例注入 Service。也就是说,在每个线程中,每次 container.Resolve<Service>() 被调用时,Decorator 的同一个实例应该被注入到 Service

的两个参数中

这是我目前的代码。我只注册了类型和它 运行,但创建了装饰器 class 的 3 个实例。在这种情况下,只有一个线程,只应创建一个 Decorator 实例。

您可以 运行 使用 DotNetFiddle:https://dotnetfiddle.net/Widget/m3PRQz

using System;
using Microsoft.Practices.Unity;

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

            container.RegisterType<IClient>(new InjectionFactory(c => new Decorator(c.Resolve<Client>())));
            container.RegisterType<ICounter, Decorator>();

            container.Resolve<Service>();

            Console.WriteLine(Decorator.NumberOfInstances + " instances of Decorator have been created");
        }
    }

    public class Client : IClient
    {
    }

    public class Decorator : IClient, ICounter
    {
        public static int NumberOfInstances { get; private set; }    
        public Decorator(IClient client)
        {
            NumberOfInstances++;
        }        
    }

    public interface ICounter
    {
    }

    public interface IClient
    {
    }

    public class Service
    {
        public Service(IClient client, ICounter counter)
        {
        }    
    }
}

编辑: 如果我不使用 DI,我会编写这段代码。请记住,为了简单起见,我没有调用任何方法。

public class Program
{
    public static void Main(string[] args)
    {
        var t1 = Task.Run(() => CreateService());
        var t2 = Task.Run(() => CreateService());
    }

    private static Service CreateService()
    {
        var decorator = new Decorator(new Client());
        return new Service(decorator, decorator);
    }
}

您可以尝试这样的操作:

为每个线程注册装饰器:

container.RegisterType<Decorator>(
    new PerThreadLifetimeManager(), 
    new InjectionFactory(c => new Decorator(c.Resolve<Client>())));

将接口映射到装饰器:

container.RegisterType<ICounter, Decorator>();
container.RegisterType<IClient, Decorator>();