分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 前端开发

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

发布时间:2023-09-06 01:06责任编辑:彭小芳关键词:.NET

在.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

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

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved