Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
289 views
in Technique[技术] by (71.8m points)

.net - Hot to register already constructed instance in unity?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...