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


    废话少说,直接上代码

    首先我们得有一个接口类和一个实现类,方便后面注入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;
            }

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

    完美!!!

  • 相关阅读:
    手写vector
    Linux文件寻址算法:逻辑地址到物理地址的转换
    东北大学操作系统实验:进程同步和通信(生产者消费者问题模拟)
    操作系统页面置换算法之FIFO,LRU
    火车进站
    进程状态转换及其PCB的变化
    iOS ViewController里代码结构的规定
    mac下搭建https服务器
    openssl生成证书
    mac下 apacha tomcat相关操作
  • 原文地址:https://www.cnblogs.com/jhli/p/9086674.html
Copyright © 2020-2023  润新知