Using Unity to create a singleton that is used in

2019-08-24 22:05发布

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条回答
在下西门庆
2楼-- · 2019-08-24 22:18

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.

查看更多
登录 后发表回答