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

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

    完美!!!

  • 相关阅读:
    前端工具Rythem介绍
    Redis持久化————AOF与RDB模式
    Hessian——轻量级远程调用方案
    JavaScript中的类数组对象
    在SpringMVC中获取request对象
    linux下,远程连接mysql
    nohup后台运行jar与关闭
    Vi常用命令
    spring mvc 重定向问题
    eclipse修改jdk后版本冲突问题
  • 原文地址:https://www.cnblogs.com/jhli/p/9086674.html
Copyright © 2011-2022 走看看