- [VB.NET] Chia sẻ source code lịch âm dương và hẹn lịch nhắc việc
- [C#] Hướng dẫn đọc thông số thiết bị Thiết bị kiểm tra Pin (HIOKI BATTERY HiTESTER BT3562)
- [VB.NET] Hướng dẫn giải captcha sử dụng dịch vụ AZCaptcha API trên winform
- [C#] Hướng dẫn chứng thực đăng nhập ứng dụng bằng vân tay (Finger Print) trên máy tính
- [C#] Color Thief cách xuất màu sắc thiết kế từ hình ảnh
- [C#] Cách tạo bản quyền và cho phép dùng thử ứng dụng Winform
- [C#] Hướng dẫn sử dụng trình duyệt web Chrome convert HTML sang tập tin file PDF
- [C#] Kết nôi điện thoại Android, IOS với App Winform via Bluetooth
- [DATABASE] Cách query cộng trừ dồn dần trong Sqlserver
- [C#] Thiết kế ứng dụng Console đẹp với thư viện Spectre.Console
- [C#] Thiết kế ứng dụng Single Instance và đưa ứng dụng lên trước nếu kiểm tra ứng dụng đang chạy
- [C#] Giới thiệu JSON Web Token và cách đọc chuỗi token
- [C#] Cách tăng giảm font chữ tất cả các control trên winform
- [DEVEXPRESS] Tích hợp chức năng Tìm kiếm Search vào CheckedComboboxEdit
- [C#] Gởi email Metting Calendar Reminder kèm nhắc thời gian lịch họp
- [C#] Tìm kiếm xem danh sách từ khóa có tồn tại trong đoạn văn bản hay không
- [C#] Thiết kế giao diện ứng dụng trên Console sử dụng thư viện Terminal.Gui
- [C#] Hướng dẫn tạo mã VietQR Payment API Winform
- [C#] Sử dụng thư viện BenchmarkDotNet đo hiệu năng của hảm Method
- [DEVEXPRESS] Tìm kiếm không dấu tô màu highlight có dấu trên C# Winform
[C#] Dependency Injection in Winform
Xin chào các bạn, bài viết hôm nay mình sẻ chia sẻ các bạn struct cấu hình để sử dụng Dependency Injection trên C#, Winform.
[C#] Dependency Injection in Winform
Dependency Injection là gì?
Theo Wikipedia:
"Trong kỹ thuật phần mềm, dependency injection là một kỹ thuật theo đó một đối tượng (hoặc static method) cung cấp các phụ thuộc của đối tượng khác. Một phụ thuộc là một đối tượng có thể được sử dụng (service)."
Nếu bạn nào viết web ASP.NET MVC thì khi tạo project template đã cấu hình sẵn cấu trúc DI sẵn cho các bạn.
Bài viết này, mình sẽ chia sẻ cấu hình DI trong C#, Winform.
Đầu tiên, các bạn cài đặt thư viện Microsoft.Extensions.Hosting
PM> Install-Package Microsoft.Extensions.Hosting -Version 7.0.0-preview.6.22324.4
Ở bài viết hiện tại, mình đang sử dụng .NET Framework 4.7.2
Thư viện Microsoft.Extensions.Hosting cung cấp cho các bạn các chức năng: DI, Logger, Configuration...
Bước 1: Cấu hình ở tập tin file program.cs
namespace DependencyInjectionWF
{
internal static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
var host = CreateHostBuilder().Build();
ServiceProvider = host.Services;
Application.Run(ServiceProvider.GetRequiredService<Form1>());
}
public static IServiceProvider ServiceProvider { get; private set; }
static IHostBuilder CreateHostBuilder()
{
return Host.CreateDefaultBuilder()
.ConfigureServices((context, services) => {
services.AddLogging(config =>
{
// config.ClearProviders();
config.AddDebug();
// config.AddConsole();
//etc
});
services.AddTransient<IHelloService, HelloService>();
services.AddTransient<Form1>();
});
}
}
}
Bước 2: Tạo 1 interface với tên IHelloService
trong này ta viết 1 phương thức SayHello
namespace DependencyInjectionWF
{
public interface IHelloService
{
string SayHello();
}
}
Bước 3: Tạo một class HelloService
chúng ta sẽ Implement từ Interface IHelloservice và viết phương thức SayHello cho nó
namespace DependencyInjectionWF
{
public class HelloService : IHelloService
{
public string SayHello()
{
return "Hello, world!";
}
}
}
Bước 4: Injection HelloService ở Form1.cs
chúng ta sẽ truyền vào ở Contructor, ở bài này mình sẽ injection thêm dịch vụ Logger
namespace DependencyInjectionWF
{
public partial class Form1 : Form
{
private readonly IHelloService helloService;
private readonly ILogger _logger;
public Form1(IHelloService helloService, ILogger<Form1> logger)
{
InitializeComponent();
this.helloService = helloService;
MessageBox.Show(helloService.SayHello());
_logger = logger;
}
private void Form1_Load(object sender, EventArgs e)
{
_logger.LogInformation("LogInformation");
_logger.LogError("LogError");
_logger.LogWarning("LogWarning");
_logger.LogTrace("LogTrace");
_logger.LogDebug("LogDebug");
_logger.LogCritical("LogCritical");
}
}
}
Thanks for watching!