Back To Home

Name: Ngày 11: Dependency Injection trong Sitecore

📌 1. Dependency Injection là gì?

Dependency Injection là kỹ thuật giúp một class “nhận” các phụ thuộc (dependencies) từ bên ngoài thay vì tự tạo ra chúng.

Ví dụ:

Không dùng DI:

 
var searchService = new SearchService();

Dùng DI:

 
public class ArticleController : Controller { private readonly ISearchService _searchService; public ArticleController(ISearchService searchService) { _searchService = searchService; } }

➡️ DI giúp code dễ test hơn, dễ mở rộng hơn, và tuân theo nguyên tắc SOLID, đặc biệt là Dependency Inversion Principle.


📌 2. DI trong Sitecore hoạt động thế nào?

Từ Sitecore 9+, DI dựa trên ASP.NET Core Dependency Injection Container, cho phép đăng ký service bằng:

  • Config patch (Sitecore cách truyền thống)

  • IServiceCollection (chuẩn .NET Core)

Sitecore sẽ load tất cả service khi khởi động pipeline.


📂 3. Vị trí đặt DI theo chuẩn Helix

Layer Vai trò DI
Foundation Đăng ký các service dùng chung cho toàn hệ thống
Feature Đăng ký service riêng của từng module
Project Hầu như không đăng ký service (chỉ dùng)

📌 Mỗi module thường có file config riêng:

 
/App_Config/Include/Foundation/Foundation.DependencyInjection.config /App_Config/Include/Feature/Feature.Search.config

🧩 4. Cách đăng ký dịch vụ trong Sitecore

Cách 1 – Dùng config patch (phổ biến trong Helix)

Ví dụ trong Foundation:

File: Foundation.DependencyInjection.config

 
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/"> <sitecore> <services> <register serviceType="MyProject.Foundation.Indexing.Services.IIndexingService, MyProject.Foundation.Indexing" implementationType="MyProject.Foundation.Indexing.Services.IndexingService, MyProject.Foundation.Indexing" lifetime="Singleton" /> </services> </sitecore> </configuration>

Các kiểu lifetime hỗ trợ:

Lifetime Ý nghĩa
Transient Tạo mới mỗi lần được gọi
Scoped Trong Sitecore tương đương Transient (không có HttpContext thực sự)
Singleton Tồn tại suốt vòng đời ứng dụng

📌 Thực tế: Sitecore dùng Transient và Singleton là chủ yếu.


🧩 5. Cách 2 – Dùng IServiceCollection (chuẩn .NET Core)

Nếu bạn dùng Sitecore 10+ với Headless hoặc ASP.NET Core rendering host, bạn có thể thêm DI như sau:

Trong Startup.cs

 
public void ConfigureServices(IServiceCollection services) { services.AddSingleton<ISearchService, SearchService>(); services.AddTransient<IArticleRepository, ArticleRepository>(); }

➕ Ưu điểm: quen thuộc với .NET Core
➖ Không dùng được trong MVC truyền thống (chỉ dành cho ASP.NET Core Rendering Host)


📌 6. Inject service vào Controller (MVC truyền thống)

Ví dụ:

 
public class ArticleController : Controller { private readonly IArticleRepository _repo; public ArticleController(IArticleRepository repo) { _repo = repo; } public ActionResult Detail() { var article = _repo.GetCurrentArticle(); return View(article); } }

Không cần tạo đối tượng bằng new nữa.


📌 7. Inject vào Rendering / Repository

DI trong Sitecore cho phép tiêm service vào:

✔ Controller

✔ Services

✔ Pipeline processors

✔ Command classes

✔ Repositories

✔ ViewModel builders

Ví dụ trong Repository:

 
public class ArticleRepository : IArticleRepository { private readonly IIndexingService _indexingService; public ArticleRepository(IIndexingService indexingService) { _indexingService = indexingService; } }

📌 8. DI và Factory – khác nhau thế nào?

Trước Sitecore 9, người ta dùng Sitecore Factory:

 
var service = Sitecore.Configuration.Factory.CreateObject("searchService", true);

📌 DI là cách hiện đại hơn, đơn giản hơn, testable hơn.


📌 9. Ví dụ module thực tế: Feature.Search

File config: Feature.Search.config

 
<services> <register serviceType="Project.Feature.Search.Services.ISearchService, Project.Feature.Search" implementationType="Project.Feature.Search.Services.SearchService, Project.Feature.Search" lifetime="Transient" /> </services>

SearchService.cs

 
public class SearchService : ISearchService { private readonly IIndexingService _indexing; public SearchService(IIndexingService indexing) { _indexing = indexing; } }

Tất cả module được đăng ký tự động khi Sitecore khởi động.


📌 10. Các lỗi DI Sitecore thường gặp

1. Circular dependency

Feature A → Feature B → Foundation C → Feature A
→ Không bao giờ được phép.

2. Quên thêm file config vào Include

Khi service không được load.

3. Inject vào class mà Sitecore không tạo instance

VD class static → không inject được.

4. Lifetime không phù hợp

Singleton nhưng chứa dữ liệu request → sai.


📌 11. Tóm tắt nhanh

Mục Nội dung
DI trong Sitecore Tích hợp .NET DI container
Nơi đăng ký Foundation & Feature
Cách đăng ký Config patch (phổ biến) hoặc IServiceCollection
Nơi sử dụng Controller, Repository, Service, Pipelines
Lợi ích Tái sử dụng, dễ test, tách module, chuẩn Helix




👉 Gợi ý bài viết tiếp theo:
🔸 “Config patch file trong App_Config/Include”

Donald Trump

Để trở thành người chiến thắng, bạn cần biết khi nào là đủ. Đôi khi trong cuộc sống, bạn phải từ bỏ cuộc chiến và chuyển sang mục tiêu mới mang lại hiệu quả hơn

Related Post