Getting the IHostEnvironment in .NET Core 3.0

Standard

Where as .NET Core 2.1 introduced the GenericHost concept to aid in constructing non-HTTP applications while leveraging primitives for DI, logging, and config, .Net Core 3.0 focused on restructuring the web hosting to be compatible with the generic host instead of having to duplicate code in multiple abstractions.
I may go into the reasons for this change in another post but as I was recently asked the question, I thought I would provide a simple example of how to leverage the IHostedEnvironment in .NET Core 3.0

First add the following 2 packages to your application:
dotnet add package Microsoft.Extensions.Hosting
dotnet add package Microsoft.Extensions.DependencyInjection

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace TestIHostEnvironment
{
    class Program
    {
        static void Main(string[] args)
        {
            var host = Host.CreateDefaultBuilder()
                .ConfigureServices((context, services) =>
                {
                    services.AddTransient<ITestService, TestService>();
                })
                .Build();

            using (var serviceScope = host.Services.CreateScope())
            {
                var serviceProvider = serviceScope.ServiceProvider;
                var testService = serviceProvider.GetRequiredService<ITestService>();

                var result = testService.DoStuff();

                Console.WriteLine(result);
            }
        }
    }
}

public interface ITestService
{
    string DoStuff();
}

public class TestService : ITestService
{
    private readonly IHostEnvironment _iHostedEnvironment;

    public TestService(IHostEnvironment iHostedEnvironment)
    {
        _iHostedEnvironment = iHostedEnvironment;
    }

    public string DoStuff()
    {
        return $"Stuff Done in {_iHostedEnvironment.EnvironmentName} environment";
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *