当前位置:网站首页>.NetCore的依赖注入
.NetCore的依赖注入
2022-07-21 22:12:00 【罗迪尼亚的熔岩】
//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>();
}
边栏推荐
- 由淺入深詳解NLP中的Adapter技術
- Niuke - Huawei question bank (91~100)
- A 15-year-old ABAP veteran's suggestion: understanding these basic knowledge is beneficial to ABAP development
- Selenium启动chrome,页面显示与隐藏事件
- Prefix and & difference
- 121. 买卖股票的最佳时机
- 贵金属入门,有以下四个方法
- How did the red team carry out the test
- 线程池配置 异步编排 CompletableFuture
- 数据安全落地方案举例让你的数据安全之路少走弯路
猜你喜欢
121. The best time to buy and sell stocks
lapsus盗取微软bing源代码的详细分析过程
贵金属入门,有以下四个方法
QGraphicsView图形视图框架使用(六)图元动画
Taishan Office Technology Lecture: which layer should the paragraph border be handled
Analysis on DNS domain name hijacking of mobile terminal in IM instant messaging development
OAuth2.0
【2022国赛模拟】最小生成树——Kruskal、矩阵、树剖动态DP
k线图基本知识占据里面重要的位置
【php环境搭建/wamp/解释器/下载】
随机推荐
Review of knowledge points (continuously updated version)
云XR平台支持沉浸式体验应用快速落地
Comprendre la technologie de l'adaptateur en NLP
Spark Learning Notes (I) -- simulating distributed computing
无代码生产新模式探索
Detailed analysis process of lapsus stealing Microsoft Bing source code
直流无刷电机工作原理
ECCV 2022 | 通过分析图像匹配解释深度伪造检测
解决anaconda中执行pip命令显示不是内部或外部命令的方法
Gb/t 30283-2022 information security technology information security service classification and code learning record
微信小程序如何实现底部弹出框封装
How can Internet enterprises ensure the security of self-developed systems
Several reasons why the chrome developer tool network shows the provision headers are shown
Microsoft SDL 2022 latest learning notes
阿里云技术专家杨泽强:弹性计算云上可观测能力构建
华为机试:叠书
k线图基本知识占据里面重要的位置
数据安全风险评估在金融行业的实际应用举例
Common terms of ad
STM32 FSMC usage notes