码迷,mamicode.com
首页 > Web开发 > 详细

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

时间:2017-08-27 17:03:05      阅读:1901      评论:0      收藏:0      [点我收藏+]

标签:新建   public   ssi   env   end   extension   logs   默认   depend   

在.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等方法了
   

 

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

标签:新建   public   ssi   env   end   extension   logs   默认   depend   

原文地址:http://www.cnblogs.com/binbinxu/p/7440531.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!