#asp.net core mvc 的视图注入
View injection is the most useful feature introduced in ASP.NET Core.
1.添加一个FruitsService
public class FruitServices
{
public List<string> GetFruits()
{
return new List<string>() { "Mango", "Apple", "Apricot", "Banana", "Grapes" };
}
}
2.Inject in View
基本语法:
@inject <service> <name>
@inject 为DI的指令
---FruitsInjection.cshtml---
@inject WebAppWithIndividualUserAccounts.Services.FruitServices fruitService
<h3>Fruit List</h3>
<ul>
@foreach (var name in fruitService.GetFruits())
{
<li>@name</li>
}
</ul>
3.配置IOC
---Startup.cs---中
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
services.AddTransient<FruitServices>();
}
ref:http://www.c-sharpcorner.com/article/view-injection-in-asp-net-core-mvc/