Using IHostingEnvironment in .NetCore library

For my .net class library all I had to do is install the following nuget package for version 2.1.0:

Microsoft.AspNetCore.Hosting.Abstractions

https://www.nuget.org/packages/Microsoft.AspNetCore.Hosting.Abstractions/

and then I just injected IHostingEnvironment into my constructor.

I didn't even need to modify Startup.cs


Note: services.AddSingleton<IHostingEnvironment>(); means you are registering IHostingEnvironment as an implementation for IHostingEnvironment in a singleton scope (always reuse).

Since you can't create an instance of an interface, you get this error.

solution

define the class you want to be created (that implements IHostingEnvironment), eg:

services.AddSingleton<IHostingEnvironment>(new HostingEnvironment());

Behind the scenes dotnet core (Hosting nuget package)

In the WebHostBuilder The first row in the constructor is:

this._hostingEnvironment = (IHostingEnvironment) new HostingEnvironment();

This hosting environment is later filled with more settings, by the webhost builder.

You should look at their github page or decompile the sources: https://github.com/aspnet/Hosting

Note: Most of the properties/settings of HostingEnvironment are set on Build() method of the WebHostBuilder. If you want to moq/test this yourself you should set these properties yourself or just also include the WebHostBuilder in your test.