microsoft-dependency-injection icon indicating copy to clipboard operation
microsoft-dependency-injection copied to clipboard

IWebHostEnvironment missing in RegisterFactory container

Open arian2ashk opened this issue 5 years ago • 8 comments

Hi, When I use unityContainer.Resolve<IWebHostEnvironment>(); on the main container it resolve it and return a value but if I use the following code and resolve IWebHostEnvironment from child container it throws exception:

unityContainer.RegisterFactory<someType>(c =>
      {
        var iWeb = c.Resolve<IWebHostEnvironment>();
        return new someType(iWeb);
      }, new SingletonLifetimeManager());

The exception:

Unity.ResolutionFailedException: 'Resolution failed with error: No public constructor is available for type Microsoft.AspNetCore.Hosting.IWebHostEnvironment.

Why Asp.net core services are not accessible in the factory?

arian2ashk avatar Jul 17 '20 09:07 arian2ashk

Did you try to explicitly register the interface?

ENikS avatar Jul 17 '20 15:07 ENikS

No because it is already registered in the asp.net core built in service provider that is then registered into unity. Do you mean that I need to resolve it from the built in service provider and register it again into Unity for it to work in the factories?

arian2ashk avatar Jul 17 '20 17:07 arian2ashk

All that is registered in core is imported into Unity. Host builder does not pass its internal registrations into user DI, some of these are implicitly created with helper functions.

You should verify if it is in the ServiceCollection that is passed into Unity. If not, just manually add it to it.

ENikS avatar Jul 17 '20 18:07 ENikS

But then how is it that I can access it from my main unity container(the container which I'm registering my other services in) by doing this: unityContainer.Resolve<IWebHostEnvironment>();

arian2ashk avatar Jul 17 '20 18:07 arian2ashk

Well, in that case I have no clue. I need a test case with reproduced error to help you.

ENikS avatar Jul 17 '20 19:07 ENikS

I created a test project https://github.com/arian2ashk/UnityAspDotNetCoreTest were you can clone and run it and see the issue. This line has a value and this line throws exception.

arian2ashk avatar Jul 17 '20 22:07 arian2ashk

Hi @ENikS any news on this issue?

arian2ashk avatar Jul 25 '20 09:07 arian2ashk

It might be a while, I am preoccupied with other things at the moment. Recovering from COVID does not help with productivity...

ENikS avatar Jul 25 '20 18:07 ENikS