unitycontainer / microsoft-dependency-injection

Unity.Microsoft.DependencyInjection package
Apache License 2.0
63 stars 36 forks source link

IWebHostEnvironment missing in RegisterFactory container #81

Open arian2ashk opened 4 years ago

arian2ashk commented 4 years ago

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?

ENikS commented 4 years ago

Did you try to explicitly register the interface?

arian2ashk commented 4 years ago

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?

ENikS commented 4 years ago

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.

arian2ashk commented 4 years ago

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

ENikS commented 4 years ago

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

arian2ashk commented 4 years ago

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 commented 4 years ago

Hi @ENikS any news on this issue?

ENikS commented 4 years ago

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