先看简单的demo代码:


using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using WebApplication1.Models;

namespace WebApplication1.Controllers
{
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
private readonly IHostEnvironment _hostEnvironment;
public HomeController(ILogger<HomeController> logger,IHostEnvironment hostEnvironment)
{
_logger = logger;
 _hostEnvironment = hostEnvironment;
}

public IActionResult Index([FromServices] IHostEnvironment hostEnvironment)
{
//1、通过构造函数注入,获取值
string path = _hostEnvironment.ContentRootPath;

//2、通过方法的FromServices注入进来,获取值
string path2 = hostEnvironment.ContentRootPath;

//通过GetRequiredService来检索服务
var hostEnvironment2 = HttpContext.RequestServices.GetRequiredService<IHostEnvironment>();
string path3= hostEnvironment2.ContentRootPath;





return View();
}

}
}
 1、通过构造函数注入,获取值
2、通过方法的FromServices注入进来,获取值
3、通过GetRequiredService来检索服务


作者:沐雪