您的位置:首页 > 理论基础 > 计算机网络

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

2017-08-27 15:41 288 查看

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

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: