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


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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM