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">