1、建立一个静态类
public class ServiceProviderInstance
{
public static IServiceProvider Instance { get; set; }
}
2、在应用初始化过程中,WebHostBuilder会利用ServiceCollection来创建新的ServiceProvider来供系统使用,所以我们在Startup类的Configure方法中,通过ApplicationBuilder的ApplicationServices属性就能获取到系统的ServiceProvider实例,在此我们利用ServiceProviderInstance的Instance属性保存当前的IServiceProvider以供系统后面使用
.net 5写法
参考:https://www.cnblogs.com/lex-wu/p/10528109.html
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
...
ServiceProviderInstance.Instance = app.ApplicationServices;
}
.net 6 写法
ServiceProviderInstance.Instance = app.Services;
参考:https://stackoverflow.com/questions/70321946/net-6-di-applicationservices-not-contains-in-webapplication
3、使用,在需要的位置通过静态属性获取对应的实例
Claims = ServiceProviderInstance.Instance.GetRequiredService<IClaimsAccessor>();
标签:core,IHttpContextAccessor,ServiceProviderInstance,获取,app,中间件,Instance,net,public From: https://www.cnblogs.com/superfeeling/p/17253695.html