1. 程式人生 > >【.netcore基礎】MVC制器Controller依賴註入

【.netcore基礎】MVC制器Controller依賴註入

singleton RF rec clas dmv ted ace tco return

廢話少說,直接上代碼

首先我們得有一個接口類和一個實現類,方便後面註入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依賴註入