分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > IT知识

【.netcore基础】MVC制器Controller依赖注入

发布时间:2023-09-06 01:56责任编辑:沈小雨关键词:MVC

废话少说,直接上代码

首先我们得有一个接口类和一个实现类,方便后面注入MVC里

接口类

 ???public interface IWeatherProvider ???{ ???????List<WeatherForecast> GetForecasts(); ???}

实现类

public class WeatherProviderFake : IWeatherProvider ???{ ???????private string[] Summaries = new[] ???????{ ???????????"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" ???????}; ???????private List<WeatherForecast> WeatherForecasts { get; set; } ???????public WeatherProviderFake() ???????{ ???????????Initialize(50); ???????} ???????private void Initialize(int quantity) ???????{ ???????????var rng = new Random(); ???????????WeatherForecasts = Enumerable.Range(1, quantity).Select(index => new WeatherForecast ???????????{ ???????????????DateFormatted = DateTime.Now.AddDays(index).ToString("d"), ???????????????TemperatureC = rng.Next(-20, 55), ???????????????Summary = Summaries[rng.Next(Summaries.Length)] ???????????}).ToList(); ???????} ???????public List<WeatherForecast> GetForecasts() ???????{ ???????????return WeatherForecasts; ???????}

Startup.cs

 ???????// This method gets called by the runtime. Use this method to add services to the container. ???????public void ConfigureServices(IServiceCollection services) ???????{ ???????????services.AddMvc(); ???????????// Simple example with dependency injection for a data provider. ???????????services.AddSingleton<IWeatherProvider, WeatherProviderFake>(); ???????}

这样IWeatherProvider就被注入到了mvc里,我们可以在控制器构造函数里这么使用了

 ???????private readonly IWeatherProvider _weatherProvider; ???????public HelloController(IWeatherProvider weatherProvider) ???????{ ???????????this._weatherProvider = weatherProvider; ???????}

源码暂不开源,有需要看的可以留邮箱。

完美!!!

【.netcore基础】MVC制器Controller依赖注入

原文地址:https://www.cnblogs.com/jhli/p/9086674.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved