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