问题
I'm try to construct HttpClient before register it in unity, but it fails at runtime with error message says HttpMessageHandler not accessible.
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:3721");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
IUnityContainer container = new UnityContainer();
container.RegisterInstance<HttpClient>(client);
IUnityContainer newcontainer = new UnityContainer();
HttpClient newclient = newcontainer.Resolve<HttpClient>();
It seems unity create another HttpClient instance using the constructor which have the most arguments.
HttpClient(HttpMessageHandler handler, bool disposeHandler);
HttpMessageHandler is abstract class, so I think this the problem my code fails at runtime. So, How can I control unity to use which construct or is there a way to that unity use already constructed instance?
回答1:
It seems unity create another HttpClient instance using the constructor which have the most arguments.
Yes, by default Unity uses the constructor with the biggest signature.
So, How can I control unity to use which constructor?
Using InjectionConstructor: newContainer.RegisterType<HttpClient>(new InjectionConstructor());
This tells Unity to use the parameterless constructor.
or is there a way to that unity use already constructed instance?
With RegisterInstance: container.RegisterInstance<HttpClient>(client);
WARNING
If you create a new container, this one does not share registrations with the first one:
MyObject instance = new MyObject();
IUnityContainer container = new UnityContainer();
container.RegisterInstance<MyObject>(instance);
Assert.AreSame(instance, container.Resolve<MyObject>());
IUnityContainer newcontainer = new UnityContainer();
Assert.AreNotSame(instance, newcontainer.Resolve<MyObject>());
来源:https://stackoverflow.com/questions/16371202/hot-to-register-already-constructed-instance-in-unity