.NET CORE 2.0之 依赖注入在类中获取IHostingEnvironment,HttpContext

在.NET CORE 中,依赖注入非常常见, 

在原先的 HttpContext中常用的server.Mappath已经么有了如下: 

HttpContext.Current.Server.MapPath(“xx“)

取而代之的是IHostingEnvironment 环境变量 

可以通过依赖注入方式来使用,不过在大多数的情况下 我们需要在,类中使用,通过传统入的方式就不太合适,如下:

技术分享

可以换一种方式来处理

 新建一个类如下:

 public static class MyServiceProvider
    {
        public static IServiceProvider ServiceProvider
        {
            get; set;
        }
    }

然后 在startup类下的Configure 方法下

MyServiceProvider.ServiceProvider = app.ApplicationServices;

 

startup下的ConfigureServices放下注册方法(这一步必不可少,但是这里可以不写,因为IHostingEnvironment 是微软默认已经帮你注册了,如果是自己的服务,那么必须注册

下面的IHttpContextAccessor 也是一样默认注册了

    services.AddSingleton<IHostingEnvironment, HostingEnvironment>();

在其他类中 使用如下:

 private static string _ContentRootPath = MyServiceProvider.ServiceProvider.GetRequiredService<IHostingEnvironment>().ContentRootPath;

 GetRequiredService 需要引用Microsoft.Extensions.DependencyInjection

使用在类中使用HttpContext同上

 public static class MyHttpContextClass
    {
        public static IServiceProvider ServiceProvider
        {
            get; set;
        }
    }

startup类下的Configure 方法下
MyHttpContextClass.ServiceProvider = app.ApplicationServices;
类中 var context= MyHttpContextClass.ServiceProvider.GetRequiredService<IHttpContextAccessor>().HttpContext;

就可以使用   context.Session等方法了
原文地址:https://www.cnblogs.com/yibinboy/p/10618120.html