Hot to register already constructed instance in unity?

你。 提交于 2019-12-12 00:38:21

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!