حقن التبعية في Views
-
في هذا الدرس بنتعلم كيف ممكن نستخدم Dependency injection مع View، حيث يدعم ASP.NET Core إدخال التبعية في Views باستخدام التوجيه inject@ بشكل مباشر دون استخدما Controller
إدخال القيم من ملف JSON
تمامًا مثل ما فعلنا في الدرس إدخال القيم من ملف JSON إلى Controllers. هذه المرة سنقوم بحقن قيم ملف mysettings.json في View مباشرة.
اكيد مثل ما تعملنا لازم نجهز التطبيق بالاعدادت المناسبه على جزء configuration لملف JSON في Startup.cs & Program.cs.ومثل ما عملنا في اعدادت الدرس السابق ما في اضافات غير الي عملنا سابقا. الآن كل ما علينا القيام به هو تنفيذ injection في View.
لذا انتقل الى SettingsController ثم أضف action جديدً باسم Show
public IActionResult Show()
{
return View();
}
الان لا بد من إضافة View لهذا ال action لذلك انقر يمين فوق هذا action ثم اختر Add View ومن ثم اختر Razor View . بعد الإضافة سيكون شكل المشروع كالتالي:

@{
Layout = null;
}
@using Microsoft.Extensions.Options;
@using DependencyInjection.Models;
@inject IOptions<MyJson> settingsOptions
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Dependency Injection</title>
<link rel="stylesheet" asp-href-include="lib/twitter-bootstrap/css/bootstrap.css" />
</head>
<body class="m-1 p-1">
<table class="table table-bordered table-sm table-striped">
<tr>
<td>Title</td>
<td>@settingsOptions.Value.Title</td>
</tr>
<tr>
<td>Version</td>
<td>@settingsOptions.Value.Version</td>
</tr>
</table>
</body>
</html>
https://localhost:44382/Settings/Show
@using Microsoft.Extensions.Configuration
@inject IConfiguration Configuration
<div>@Configuration["Logging:LogLevel:Default"]</div>
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"Middleware": {
"EnableContentMiddleware": true,
"EnableShortCircuitMiddleware": true,
"EnableRequestEditingMiddleware": true,
"EnableResponseEditingMiddleware": false
},
"ConnectionStrings": {
"DefaultConnection": "Server=DESKTOP-H4I6449\\HATEMSERVER;Database=StudentsAcademy;User Id=admin;Password=admin@@$$;"
}
}
public IActionResult appsettings()
{
return View();
}

@{
Layout = null;
}
@using Microsoft.Extensions.Configuration
@inject IConfiguration Configuration
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Dependency Injection</title>
<link href="~/lib/bootstrap/dist/css/bootstrap.css" rel="stylesheet" />
</head>
<body class="m-1 p-1">
<table class="table table-bordered table-sm table-striped">
<tr>
<td>Default</td>
<td>@Configuration["Logging:LogLevel:Default"]</td>
</tr>
<tr>
<td>Microsoft</td>
<td>@Configuration["Logging:LogLevel:Microsoft"]</td>
</tr>
<tr>
<td>Microsoft.Hosting.Lifetime</td>
<td>@Configuration["Logging:LogLevel:Microsoft.Hosting.Lifetime"]</td>
</tr>
</table>
</body>
</html>
https://localhost:44382/settings/appsettings

اترك تعليقك