Reputation: 4811
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?
Upvotes: 1
Views: 4106
Reputation: 1057
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.
Upvotes: 3