如今,ASP.NET MVC 6 支持注入类到视图中,和VC类不一样的是,对类是公开的、非嵌套或非抽象并无限制。在这个例子中,咱们建立了一个简单的类,用于统计代办事件、已完成事件和平均优先级的服务。html
StatisticsService 类代码设计以下:数据库
System.Linq;
System.Threading.Tasks;
TodoList.Models;
TodoList.Services
{
StatisticsService
{
ApplicationDbContext db;
StatisticsService(ApplicationDbContext context)
{
db = context;
}
async Task<int> GetCount()
{
await Task.FromResult(db.TodoItems.Count());
}
async Task<int> GetCompletedCount()
{
await Task.FromResult(
db.TodoItems.Count(x => x.IsDone == ));
}
async Task<> GetAveragePriority()
{
await Task.FromResult(
db.TodoItems.Average(x =>
(?)x.Priority) ?? 0.0);
}
}
}
@inject TodoList.Services.StatisticsService Statisticsc#
添加标记调用 StatisticsService:浏览器
<div>@Html.ActionLink("", "", "") </div>
</div>
<div ="">
@await Component.InvokeAsync("", 4, )
<h3>Stats</h3>
<ul>
<li>Items: @await Statistics.GetCount()</li>
<li>Completed:@await Statistics.GetCompletedCount()</li>
<li>Average Priority:@await Statistics.GetAveragePriority()</li>
</ul>
</div>
</div>
如下是该文件的完整代码:服务器
@inject TodoList.Services.StatisticsService Statistics
@{
ViewBag.Title = "";
}
<div ="">
<h1>ASP.NET vNext</h1>
</div>
<div ="">
<div ="">
@ (Model.Count == 0)
{
<h4>No Todo Items</h4>
}
else
{
<table>
<tr><th>TODO</th><th></th></tr>
@foreach (var todo Model)
{
<tr>
<td>@todo.Title </td>
<td>
@Html.ActionLink("", "", "", { id = todo.Id }) |
@Html.ActionLink("", "", "", { id = todo.Id }) |
@Html.ActionLink("", "", "", { id = todo.Id })
</td>
</tr>
}
</table>
}
<div>@Html.ActionLink("", "", "") </div>
</div>
<div ="">
@await Component.InvokeAsync("", 4, )
<h3>Stats</h3>
<ul>
<li>Items: @await Statistics.GetCount()</li>
<li>Completed:@await Statistics.GetCompletedCount()</li>
<li>Average Priority:@await Statistics.GetAveragePriority()</li>
</ul>
</div>
</div>
// This method gets called by the runtime.
void ConfigureServices(IServiceCollection services)
{
// Add EF services the services container.
services.AddEntityFramework(Configuration)
.AddSqlServer()
.AddDbContext<ApplicationDbContext>();
// Add Identity services the services container.
services.AddDefaultIdentity<ApplicationDbContext, ApplicationUser, IdentityRole>(Configuration);
// Add MVC services the services container.
services.AddMvc();
services.AddTransient<TodoList.Services.StatisticsService>();
}
如下是效果图:asp.net
发布应用到公有云,你须要申请 Microsoft Azure 账号,若是没有,能够经过如下连接注册:activate your MSDN subscriber benefits 或 sign up for a free trial.async
数据库服务器是一个宝贵的资源。最好使用现有服务器进行测试和开发。然而因为没有密码校验机制,密码输入错误时不会有错误提示,只有在应用实际访问数据库时才会报错。工具
原文连接:http://www.asp.net/vnext/overview/aspnet-vnext/vc#inj开发工具
以上内容,介绍了如何向视图中添加服务和发布应用到公有云中,你们能够将这些知识运用到实际开发中。开发时还能够借助一些工具。ComponentOne Studio for ASP.NET 是ASP.NET平台上的一整套完备的开发工具包,用于在各类浏览器中建立和设计具备现代风格的Web应用程序。测试