想要统一注册已经构建的实例? [英] Hot to register already constructed instance in unity?

查看:21
本文介绍了想要统一注册已经构建的实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试在统一注册之前构造 HttpClient,但它在运行时失败,错误消息说 HttpMessageHandler 不可访问.

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>();

似乎 unity 使用具有最多参数的构造函数创建了另一个 HttpClient 实例.

It seems unity create another HttpClient instance using the constructor which have the most arguments.

HttpClient(HttpMessageHandler handler, bool disposeHandler);

HttpMessageHandler 是抽象类,所以我认为这是我的代码在运行时失败的问题.那么,我如何控制统一使用哪个构造,或者有没有办法让统一使用已经构造的实例?

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?

推荐答案

似乎 unity 使用具有最多参数的构造函数创建了另一个 HttpClient 实例.

It seems unity create another HttpClient instance using the constructor which have the most arguments.

是的,默认情况下 Unity 使用具有最大签名的构造函数.

Yes, by default Unity uses the constructor with the biggest signature.

那么,我如何控制 unity 使用哪个构造函数?

So, How can I control unity to use which constructor?

使用 InjectionConstructor:newContainer.RegisterType(new InjectionConstructor());这告诉 Unity 使用无参数构造函数.

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?

使用注册实例:container.RegisterInstance(client);

如果你创建一个新的容器,这个容器不会和第一个共享注册:

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>());

这篇关于想要统一注册已经构建的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆