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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM