Rainer Rainer - 14 days ago 8
C# Question

Access IApplicationEnvironment in ConfigureServices

In my

ConfigureServices
method I want to read a file (in my case a certificate used for signing tokens, but it could be any file necessary for setting up services). Therefore I need to know the
ApplicationBasePath
from
IApplicationEnvironment
.

Currently I solve the problem by getting the
IApplicationEnvironment
service like this:

public void ConfigureServices(IServiceCollection services)
{
...
string basePath;
var serviceProvider = services.BuildServiceProvider();
try
{
basePath = serviceProvider.GetRequiredService<IApplicationEnvironment>().ApplicationBasePath;
}
finally
{
(serviceProvider as IDisposable)?.Dispose();
}
...
}


This approach works but I am not sure if that's the right approach. So my questions are:


  1. Is there a better way to read a file in
    ConfigureServices
    ?

  2. Is there a better way to get the application base path in
    ConfigureServices
    ?

  3. If my approach is correct, do I handle
    IDisposable
    correctly?


Answer

The runtime allows dependency injection in the constructor of the Startup class:

public class Startup
{
    private readonly IApplicationEnvironment _appEnv;

    public Startup(IApplicationEnvironment appEnv)
    {
        _appEnv = appEnv;
    }

    public void ConfigureServices(IServiceCollection services)
    {
        string basePath = _appEnv.ApplicationBasePath;
    }
}