如今,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應用程序。測試