使用 Unity 创建一个在我的 Class 中使用的单例

Using Unity to create a singleton that is used in my Class

我有一个 class 需要一个 HttpClient class 的实例,我只想实例化一次,即 Singleton

public interface IMyClass {}
public class MyClass : IMyClass {
    private HttpClient client;
    public MyClass(HttpClient client)
    {
        this.client = client;
    }
}


IUnityContainer container = new UnityContainer();
container.RegisterType<IMyClass, MyClass>();

var httpClient = new HttpClient();

如何将 httpClient 实例注册为我的单例 MyClass 可以使用它?

你试过这个吗?

container.RegisterType<IMyClass, MyClass>(new ContainerControlledLifetimeManager());

https://msdn.microsoft.com/en-us/library/ff647854.aspx

由于您的 class 只有一个实例,其中也只有一个 HTTP 客户端实例。

更新:

为了解决 HttpClient 依赖本身,使用

container.RegisterType<HttpClient, HttpClient>(new ContainerControlledLifetimeManager(), new InjectionConstructor());

这样任何需要 HttpClient 的 class 都将收到它的相同实例。我不确定参数的顺序,但基本上你必须告诉 Unity 2 件事 - 将 HttpClient 注册为单例并使用其默认构造函数。