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

寵の児 提交于 2019-12-12 05:28:38

问题


I have a class that needs an instance of a HttpClient class, which I want to be instantiated only once i.e. 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();

How can I register the httpClient instance as a singleton to my MyClass can use it?


回答1:


Have you tried this?

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

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

Since there will be only one instance of your class, there will also one only one instance of HTTP client inside it.

Update:

In order to resolve HttpClient dependency itself, use

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

That way any class that needs HttpClient will receive the same instance of it. I'm not sure about the order of parameters, but basically you have to tell Unity 2 things - to register HttpClient as a singleton and to use its default constructor.



来源:https://stackoverflow.com/questions/44912474/using-unity-to-create-a-singleton-that-is-used-in-my-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!