1

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?

2
  • Why do you want to have a single instance of HttpClient ? Commented Jul 4, 2017 at 18:57
  • 4
    @Itsik Most likely because HTTP client was designed to be used as a singleton. I personally don't recommend using it per-request. Commented Jul 4, 2017 at 19:00

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

8 Comments

I want to use HttpClient in other classes also, not just in MyClass.
I don't see you registering the class HttpClient anywhere? How would that work?
Would you like it to be Singleton for all classes or a separate instance for each of them?
Singleton for all classes that need a HttpClient.
It's because Unity tries to create HttpMessageHandler for you. You can specify the constructor directly using new InjectionConstructor() inside RegisterType to use a parameterless one.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.