【.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;
        }

 

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

 

完美!!!

 

posted @ 2018-05-25 09:13  0539  阅读(403)  评论(0编辑  收藏  举报