zoukankan      html  css  js  c++  java
  • 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">
    
  • 相关阅读:
    Android 测试工具集01
    Android ImageView的ScaleType属性
    Android Webview与Html5交互
    Java Notes 00
    Android 显示原理简介
    Android开发在路上:少去踩坑,多走捷径
    Android_Dialog cancle 和dismiss 区别
    SpringMVC框架
    Redis持久化
    Redis集群
  • 原文地址:https://www.cnblogs.com/liflower/p/13894336.html
Copyright © 2011-2022 走看看