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

來源:互聯網
上載者:User

標籤:建立   public   ssi   env   end   extension   logs   預設   depend   

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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.