1. 程式人生 > 其它 >.NET CORE 2.0之 依賴注入在類中獲取IHostingEnvironment,HttpContext

.NET CORE 2.0之 依賴注入在類中獲取IHostingEnvironment,HttpContext

技術標籤:.net core依賴注入

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

複製程式碼