Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using IHostingEnvironment in .NetCore library

I build an ASP.NET Core application and I create a .NET Core Class Library for unit testing.

I want to use IHostingEnvironment in my library (to get physical path of a file), so I've added this line to Startup.cs of my ASP.NET Core application :

services.AddSingleton<IHostingEnvironment>();

In the Library I've added reference to my ASP.NET application, and in my class I wrote this:

private IHostingEnvironment _env;
public Class1(IHostingEnvironment env)
{
    _env = env;
}

But when I run it then it gives me this error:

the following constructor parameters did not have matching fixture date : IHostingEnvironment env

What is the problem? How can I use it in .NET Core Class Library?


EDIT: I tried to use this too:

IServiceCollection services = new ServiceCollection();
services.AddSingleton<IHostingEnvironment>();
IServiceProvider provider = services.BuildServiceProvider();
IHostingEnvironment service = provider.GetService<IHostingEnvironment>();
var p = service.WebRootPath; 

The last one gives me this error:

Cannot instantiate implementation type 'Microsoft.AspNetCore.Hosting.IHostingEnvironment' for service type 'Microsoft.AspNetCore.Hosting.IHostingEnvironment'

like image 808
pejman Avatar asked Dec 27 '16 09:12

pejman


People also ask

What is IHostingEnvironment?

The IHostingEnvironment is an interface for . Net Core 2.0. The IHostingEnvironment interface need to be injected as dependency in the Controller and then later used throughout the Controller. The IHostingEnvironment interface have two properties.

What is the purpose of IHostingEnvironment interface in ASP.NET Core?

What is the purpose of IHostingEnvironment interface in ASP.NET Core? Provides information about the web hosting environment an application is running in.

How do you use IWebHostEnvironment in CS?

In your main program, you can create an application builder and an application. The Environment (as a IWebHostEnvironment ) is available on both objects. var builder = WebApplication. CreateBuilder(args); var environment = builder.

What is the use of IWebHostEnvironment?

IWebHostEnvironment is an interface used to provide info about hosting & can get data about path from it why i take an instance from it and inject it like i was inject a _db without register it in ConfigureServices method like i register Db context?!


1 Answers

This worked for me in both .net core class library and console application:

Using references,

using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Hosting.Internal;

Adding DI registration,

services.AddSingleton<IHostingEnvironment, HostingEnvironment>();
like image 112
Reyan Chougle Avatar answered Oct 25 '22 08:10

Reyan Chougle