zoukankan      html  css  js  c++  java
  • 【.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;
            }

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

    完美!!!

  • 相关阅读:
    python中os.listdir( )函数读取文件夹
    斐讯k2p 月光银 硬件版本A2-软件版本22.7.8.5 刷官改系统
    Ubuntu 16.04 换国内源
    pip和apt-get换源
    Python-OpenCV中的filter2D()函数
    Python-OpenCV中图像合并显示
    Python-OpenCV——Image Blurring(Image Smoothing)
    Python-OpenCV中的resize()函数
    删除Chrome地址栏记录中自动补全的网址
    Python中Numpy mat的使用
  • 原文地址:https://www.cnblogs.com/jhli/p/9086674.html
Copyright © 2011-2022 走看看