从作用域服务工厂获取主机名

Die*_*hon 4 dependency-injection asp.net-core-mvc asp.net-core

我正在创建的其中一个服务需要当前主机名作为参数(不同的请求使用不同的主机名,这会影响我的服务使用的外部资源):

public class Foo
{
    public Foo(string host) {...}
}
Run Code Online (Sandbox Code Playgroud)

我正在将其注册为作用域:

public void ConfigureServices(IServiceCollection services)
{
    services.AddScoped(s => new Foo(/* get host name for the current request */));
}
Run Code Online (Sandbox Code Playgroud)

在这一点上获取主机名的最简洁方法是什么?


更新:我想出了这个:

private static Foo GetFoo(IServiceProvider services)
{
    var contextAccessor = services.GetRequiredService<IHttpContextAccessor>();
    var host = contextAccessor.HttpContext.Request.Host.Value;
    return new Foo(host);
}
Run Code Online (Sandbox Code Playgroud)

它是一个好的/支持的解决方案,还是一个黑客?

Mat*_*rey 5

由于您已经正确地将其定义为范围,因此您可以IHttpContextAccessor直接在Foo的构造函数中使用它:

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

一些类似很多地方在GitHub的仓库; 它看起来像一个完美的模式.