dependency-injection – 从作用域服务工厂获取主机名

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

public class Foo
{
    public Foo(string host) {...}
}

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

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

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

更新:我想出了这个:

private static Foo GetFoo(IServiceProvider services)
{
    var contextAccessor = services.GetrequiredService<IHttpContextAccessor>();
    var host = contextAccessor.HttpContext.Request.Host.Value;
    return new Foo(host);
}

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

解决方法

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

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

在GitHub存储库中similardone很多places;它看起来像一个完美的模式.

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....