One of the services I create requires the current host name as a parameter (different requests use different host names, which affects the external resources used by my service):
public class Foo
{
public Foo(string host) {...}
}
I register it as a scope:
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped(s => new Foo());
}
What is the cleanest way to get the hostname at this point?
Update: I came up with the following:
private static Foo GetFoo(IServiceProvider services)
{
var contextAccessor = services.GetRequiredService<IHttpContextAccessor>();
var host = contextAccessor.HttpContext.Request.Host.Value;
return new Foo(host);
}
Is this a good / supported solution or hack?
source
share