Retrieving a hostname from a factory limited service

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(/* get host name for the current request */));
}

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?

+4
source share
1 answer

Since you correctly define it as a scope, you can use IHttpContextAccessorFoo directly in your constructor:

public class Foo
{
    public Foo(IHttpContextAccessor contextAccessor) 
    {
        var host = contextAccessor.HttpContext.Request.Host.Value;
        // remainder of constructor logic here
    }
}

- done many GitHub; , .

+5

All Articles