先看简单的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来检索服务


​ 作者:沐雪

文章均系作者原创或翻译,如有错误不妥之处,欢迎各位批评指正。本文版权归作者所有,如需转载恳请注明。
​​​ 为之网-热爱软件编程 http://www.weizhi.cc/​