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