• ASP.NET Core MVC 泛型接口的声明调用与注入服务


    创建接口 where T:class 指定T只能是类型

        public interface ITest<T> where T:class
        {
            IEnumerable<T> GetAll();
        }
    

    实现:

        public class TestClass : ITest<Factory>
        {
            public IEnumerable<Factory> GetAll()
            {
                return new List<Factory> { 
                new Factory()
                { 
                Name="我是工厂一"
                },
                new Factory()
                {
                Name="我是工厂二"
                },
                new Factory()
                {
                Name="我是工厂三"
                }
                };
            }
        }
    

    serviceProvider容器的添加服务

                services.AddScoped<ITest<Factory>, TestClass>();
    

    控制器中的注入服务(构造方法)

        public class ProductController : Controller
        {
            private readonly ITest<Factory> _test;
    
            public ProductController(ITest<Factory> test)
            {
                this._test = test;
            }
    
          //控制器
    
          }
    

    视图中的使用

    @model IEnumerable<TestMvc.Factory>
    <div class="jumbotron jumbotron-fluid">
        <div class="container">
            @foreach (var item in Model)
            {
                <h1 class="display-4">@item.Name</h1>
            }
    
            <p class="lead">This is a modified jumbotron that occupies the entire horizontal space of its parent.</p>
        </div>
    </div class="jumbotron jumbotron-fluid">
    
  • 相关阅读:
    密码数学大作业
    《数据结构》教材测评
    机器学习概述
    SQL基础-流程控制结构
    SQL基础-变量 存储过程和函数
    SQL基础-视图
    SQL基础-TCL 事务控制语言
    SQL基础-DDL 数据定义语言
    SQL基础-DML 数据操作语言
    SQL基础 -DQL 数据查询语言(下)
  • 原文地址:https://www.cnblogs.com/liflower/p/13894336.html
Copyright © 2020-2023  润新知