Skip to content

Commit

Permalink
IServiceCollection
Browse files Browse the repository at this point in the history
  • Loading branch information
XuanThuLab committed Aug 29, 2020
1 parent a4a4257 commit 119b7a5
Show file tree
Hide file tree
Showing 22 changed files with 8,219 additions and 0 deletions.
8 changes: 8 additions & 0 deletions ASP_NET_CORE/04.ServiceCollection/04.ServiceCollection.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
<RootNamespace>_04.ServiceCollection</RootNamespace>
</PropertyGroup>

</Project>
41 changes: 41 additions & 0 deletions ASP_NET_CORE/04.ServiceCollection/Controller/ProductController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using System.Text;
using System.Linq;

namespace _04.ServiceCollection
{
public class ProductController
{
IListProductName lsPhone;
IListProductName lsLaptop;

// Inject hai dịch vụ qua phương thức khởi tạo
public ProductController(IListProductName lsphone, LaptopName lslaptop) {
Console.WriteLine(this.GetType().Name + " created");
this.lsPhone = lsphone;
this.lsLaptop = lslaptop;
}

// Xuất danh sách sản phẩm cho Response
public async Task List(HttpContext context) {

var sb = new StringBuilder();
string lsPhoneHTML = string.Join("", lsPhone.GetNames().Select(name => name.HtmlTag("li"))).HtmlTag("ul");
string lsLaptopHTML = string.Join("", lsLaptop.GetNames().Select(name => name.HtmlTag("li"))).HtmlTag("ul");
sb.Append("Danh sách điện thoại".HtmlTag("h2"));
sb.Append(lsPhoneHTML);

sb.Append("Danh sách Laptop".HtmlTag("h2"));
sb.Append(lsLaptopHTML);

string menu = HtmlHelper.MenuTop(HtmlHelper.DefaultMenuTopItems(), context.Request);
string html = HtmlHelper.HtmlDocument("DS Sản phẩm", menu + sb.ToString().HtmlTag("div", "container"));

context.Response.StatusCode = 200;
await context.Response.WriteAsync(html);
}
}
}
142 changes: 142 additions & 0 deletions ASP_NET_CORE/04.ServiceCollection/HtmlHelper.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
using System.Collections.Generic;
using Microsoft.AspNetCore.Http;
using System.Text;

public static class HtmlHelper
{
/// <summary>
/// Phát sinh trang HTML
/// </summary>
/// <param name="title">Tiêu đề trang</param>
/// <param name="content">Nội dung trong thẻ body</param>
/// <returns>Trang HTML</returns>
public static string HtmlDocument(string title, string content) {
return $@"
<!DOCTYPE html>
<html>
<head>
<meta charset=""UTF-8"">
<title>{title}</title>
<link rel=""stylesheet"" href=""/css/site.min.css"" />
<script src=""/js/jquery.min.js"">
</script><script src=""/js/popper.min.js"">
</script><script src=""/js/bootstrap.min.js""></script>
</head>
<body>
{content}
</body>
</html>";
}


/// <summary>
/// Phát sinh HTML thanh menu trên, menu nào active phụ thuộc vào URL mà request gủi đến
/// </summary>
/// <param name="menus">Mảng các menu item, mỗi item có cấu trúc {url, lable}</param>
/// <param name="request">HttpRequest</param>
/// <returns></returns>

public static string MenuTop(object[] menus, HttpRequest request) {

var menubuilder = new StringBuilder();
menubuilder.Append("<ul class=\"navbar-nav\">");
foreach (dynamic menu in menus) {
string _class = "nav-item";
// Active khi request.PathBase giống url của menu
if (request.PathBase == menu.url) _class += " active";
menubuilder.Append($@"
<li class=""{_class}"">
<a class=""nav-link"" href=""{menu.url}"">{menu.label}</a>
</li>
");
}
menubuilder.Append("</ul>\n");

string menuhtml = $@"
<div class=""container"">
<nav class=""navbar navbar-expand-lg navbar-dark mainbackground"">
<a class=""navbar-brand"" href=""/"">XTLAB</a>
<button class=""navbar-toggler"" type=""button""
data-toggle=""collapse"" data-target=""#my-nav-bar""
aria-controls=""my-nav-bar"" aria-expanded=""false"" aria-label=""Toggle navigation"">
<span class=""navbar-toggler-icon""></span>
</button>
<div class=""collapse navbar-collapse"" id=""my-nav-bar"">
{menubuilder}
</div>
</nav></div>";

return menuhtml;
}

/// <summary>
/// Những menu item mặc định cho trang
/// </summary>
/// <returns>Mảng các menuitem</returns>
public static object[] DefaultMenuTopItems() {
return new object[] {
new {
url = "/RequestInfo",
label = "Request"
},
new {
url = "/Form",
label = "Form"
}
,
new {
url = "/Encoding",
label = "Encoding"
},
new {
url = "/Cookies",
label = "Cookies"
},
new {
url = "/Json",
label = "JSON"
}
};
}

public static string HtmlTrangchu() {
return $@"
<div class=""container"">
<div class=""jumbotron"">
<h1 class=""display-4"">Đây là một trang Web .NET Core</h1>
<p class=""lead"">Trang Web này xây dựng trên nền tảng <code>.NET Core</code>,
chưa sử dụng kỹ thuật MVC - nhằm mục đích học tập.
Mã nguồn trang này tại <a target=""_blank""
href=""https://github.com/xuanthulabnet/learn-cs-netcore/blob/master/ASP_NET_CORE/03.RequestResponse/"">
Mã nguồn Ví dụ</a>
</p>
<hr class=""my-4"">
<p><code>.NET Core</code> là một hệ thống chạy đa nền tảng (Windows, Linux, macOS)</p>
<a class=""btn btn-danger btn-lg"" href=""https://xuanthulab.net/lap-trinh-c-co-ban/"" role=""button"">Xem thêm</a>
</div>
</div>
";

}

// Mở rộng String, phát sinh thẻ HTML với nội dụng là String
// Ví dụ:
// "content".HtmlTag() => <p>content</p>
// "content".HtmlTag("div", "text-danger") => <div class="text-danger">content</div>
public static string HtmlTag(this string content, string tag = "p", string _class = null) {
string cls = (_class != null) ? $" class=\"{_class}\"":null;
return $"<{tag + cls}>{content}</{tag}>";
}
public static string td(this string content, string _class = null) {
return content.HtmlTag("td", _class);
}
public static string tr(this string content, string _class = null) {
return content.HtmlTag("tr", _class);
}
public static string table(this string content, string _class = null) {
return content.HtmlTag("table", _class);
}


}
26 changes: 26 additions & 0 deletions ASP_NET_CORE/04.ServiceCollection/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace _04.ServiceCollection
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}

public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
27 changes: 27 additions & 0 deletions ASP_NET_CORE/04.ServiceCollection/Properties/launchSettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:10208",
"sslPort": 44346
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"_04.ServiceCollection": {
"commandName": "Project",
"launchBrowser": true,
"applicationUrl": "https://localhost:5001;http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
using System.Collections.Generic;
using System.Collections;

public interface IListProductName
{
// Trả về danh sách các tên
IEnumerable<string> GetNames();
}
15 changes: 15 additions & 0 deletions ASP_NET_CORE/04.ServiceCollection/Services/LaptopName.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
using System.Collections.Generic;
using System.Collections;

public class LaptopName : IListProductName
{
public LaptopName() => System.Console.WriteLine("LaptopName Created");
// Mảng tên sản phẩm
string[] laptops = new string[] {
"Apple MacBook Pro 13 inch", "HP Spectre X360", "Samsung Chromebook Pro"};

public IEnumerable<string> GetNames()
{
return laptops;
}
}
14 changes: 14 additions & 0 deletions ASP_NET_CORE/04.ServiceCollection/Services/PhoneName.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
using System.Collections.Generic;
using System.Collections;
public class PhoneName : IListProductName
{
public PhoneName() => System.Console.WriteLine("PhoneName created");
// Mảng tên các điện thoại
private List<string> phone_names = new List<string> {
"Iphone 7", "Samsung Galaxy", "Nokia 123"
};
public IEnumerable<string> GetNames()
{
return phone_names;
}
}
82 changes: 82 additions & 0 deletions ASP_NET_CORE/04.ServiceCollection/Startup.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace _04.ServiceCollection {
public class Startup {
IServiceCollection _services;


public void ConfigureServices (IServiceCollection services) {

services.AddSingleton<IListProductName, PhoneName> (); // đăng ký dịch vụ, đối tượng chỉ tạo một lần
services.AddTransient<LaptopName, LaptopName> (); // đăng ký dịch vụ, tạo mới mỗi lần triệu gọi
services.AddTransient<ProductController, ProductController> ();
_services = services;


}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure (IApplicationBuilder app, IWebHostEnvironment env) {
if (env.IsDevelopment ()) {
app.UseDeveloperExceptionPage ();
}

app.UseStaticFiles ();

app.UseRouting ();

app.Map ("/Product", app => {
app.Run (async (context) => {
// Gọi đến dịch vụ ProductController
var productcontroller = app.ApplicationServices.GetService<ProductController> ();
await productcontroller.List (context);
});
});

app.MapWhen (
(context) => {
return context.Request.Path.Value.StartsWith ("/Abcxyz");
},

appProduct => {
appProduct.Run (async (context) => {
await appProduct.ApplicationServices.GetService<ProductController> ().List (context);
});
});

app.Map ("/allservice", app01 => {
app01.Run (async (context) => {
var stringBuilder = new StringBuilder ();
stringBuilder.Append ("<tr><th>Tên</th><th>Lifetime</th><th>Tên đầy đủ</th></tr>");
foreach (var service in _services) {
string tr = service.ServiceType.Name.ToString ().HtmlTag ("td") +
service.Lifetime.ToString ().HtmlTag ("td") +
service.ServiceType.FullName.HtmlTag ("td");
stringBuilder.Append (tr.HtmlTag ("tr"));
}
string htmlallservice = stringBuilder.ToString ().HtmlTag ("table", "table table-bordered table-sm");
string html = HtmlHelper.HtmlDocument ("Các dịch vụ", (htmlallservice));
await context.Response.WriteAsync (html);
});
});

app.UseEndpoints (endpoints => {
endpoints.MapGet ("/", async context => {
await context.Response.WriteAsync ("Hello World!");
});
});
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
}
}
10 changes: 10 additions & 0 deletions ASP_NET_CORE/04.ServiceCollection/appsettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
}
Loading

0 comments on commit 119b7a5

Please sign in to comment.