dependency-injection - 从范围服务工厂获取主机名

标签 dependency-injection asp.net-core asp.net-core-mvc

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

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);
}

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

最佳答案

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

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

东西similardone许多 places在 GitHub 存储库中;它看起来是一个完美的模式。

关于dependency-injection - 从范围服务工厂获取主机名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29945442/

相关文章:

javascript - 获取类构造函数参数名称

c# - 为多个客户自定义 c# WinForm 应用程序

asp.net-core - ASP.NET Core 从 IMemoryCache 清除缓存(由 CacheExtensions 类的 Set 方法设置)

asp.net core 2 Angular 模板 - 在哪里添加第三方 Assets

c# - .Net 核心 2.2 未将 302 的状态代码更新为 401。OnRedirectToLogin 事件未触发

asp.net-mvc-2 - 如何在 Ninject 中为 MVC 中的 ValidationAttribute 进行属性注入(inject)?

c# - OwinStartup时如何使用DI容器

c# - 将 Serilog 与 Azure 应用程序见解和 .Net Core 结合使用

javascript - 从循环内发布表单数据

c# - AdalSilentTokenAcquisitionException : Failed to acquire token silently as no token was found in the cache. 调用方法 AcquireToken