使用Unity创建我的课程中使用的单例 [英] Using Unity to create a singleton that is used in my Class
问题描述
我有一个需要HttpClient类实例的类,我只想实例化一次,即Singleton
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();
如何将httpClient实例作为单例注册到我的 MyClass
可以使用它吗?
How can I register the httpClient instance as a singleton to my MyClass
can use it?
推荐答案
您尝试过吗?
container.RegisterType<IMyClass, MyClass>(new ContainerControlledLifetimeManager());
https://msdn.microsoft.com/zh-CN/library/ff647854.aspx
自
更新:
为了解决HttpClient依赖关系本身,请使用
In order to resolve HttpClient dependency itself, use
container.RegisterType<HttpClient, HttpClient>(new ContainerControlledLifetimeManager(), new InjectionConstructor());
这样,任何需要HttpClient的类都将收到它的相同实例。我不确定参数的顺序,但是基本上您必须告诉Unity 2事情-将HttpClient注册为单例并使用其默认构造函数。
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.
这篇关于使用Unity创建我的课程中使用的单例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!