.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等方法了
相关文章推荐
- [C#].Net Core 获取 HttpContext.Current 以及 AsyncLocal 与 ThreadLocal
- 为什么获取的System.Web.HttpContext.Current值为null,HttpContext对象为null时如何获取程序(站点)的根目录
- AngularJS http拦截器依赖注入$http
- 尽可能摆脱对HttpContext的依赖
- Spring IOC/BeanFactory/ApplicationContext的工作流程/实现原理/初始化/依赖注入源码详解
- .net core 依赖注入扩展,实现随处控制反转
- .net System.Web.HttpContext.Current.Session 获取值出错(在Page继承类的构造函数中出错)
- Spring MVC中如何通过RequestContextHolder类获取HttpServletRequest和HttpSession
- Unity&Webform(2):自定义LifetimeManager和TypeConverter使Unity从HttpContext中取值注入WebForm页面 (转)
- 艾伟:尽可能摆脱对HttpContext的依赖
- 深入 Unity 1.x 依赖注入容器之三:获取对象
- NET Core 中的依赖注入
- .net core依赖注入的封装
- 在.net Core 中像以前那样的使用HttpContext.Current
- .net System.Web.HttpContext.Current.Session 获取值出错(一般处理程序中出错)
- NET Core,你必须了解无处不在的“依赖注入”
- android lib或依赖项目中无法通过application获取Context的
- 关于HttpContext.Current.Request获取值 【转】
- Spring-Context之六:基于Setter方法进行依赖注入
- 依赖注入的威力,.NET Core的魅力:解决MVC视图中的中文被html编码的问题