//MVC自带的三种依赖注入方式
//MVC自带的三种依赖注入方式
public WeatherForecastController(ILogger<WeatherForecastController> logger, IConfiguration configuration, IHostEnvironment hostEnvironment)
{
_logger = logger;
this.configuration = configuration;
this.hostEnvironment = hostEnvironment;
}
[HttpGet]
public IEnumerable<WeatherForecast> Get()
{
var rng = new Random();
//第二种依赖注入方式
IHostEnvironment host = HttpContext.RequestServices.GetService(typeof(IHostEnvironment)) as IHostEnvironment;
//第三种依赖注入方式
var host2 = HttpContext.RequestServices.GetRequiredService<IHostEnvironment>();
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = rng.Next(-20, 55),
Summary = Summaries[rng.Next(Summaries.Length)]
})
.ToArray();
}
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddSingleton<IServiceCollection>();//每次都是原来的那个
services.AddScoped<ILogger>(); //本次进入Controller的URL 获取的都是一样的
services.AddTransient<ILogger>(); //每次都是新的
services.AddSingleton<IServiceCollection>(x => new ServiceCollection());
//等同于
services.AddSingleton<IServiceCollection, ServiceCollection>();
}