What is IoC (DI) Container?
What is IoC (DI) Container?
An IoC (Inversion of Control) Container, also known as a Dependency Injection (DI) Container, is a framework used in software development to manage the creation, configuration, and lifecycle of dependencies. In the context of .NET Core, the IoC container is a built-in feature that simplifies the process of dependency injection, which is a design pattern aimed at achieving Inversion of Control between classes and their dependencies.
Registration: The IoC container needs to know which type of object to create for a specific dependency. This is done by registering services in the ConfigureServices method of the Startup class. For example:
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IMessageService, MessageService>();
}
This registers MessageService as a singleton implementation of IMessageService.
Resolution: The IoC container resolves dependencies by creating instances of the registered services and injecting them into the requesting classes. This is typically done through constructor injection:
public class MyClass
{
private readonly IMessageService _messageService;
public MyClass(IMessageService messageService)
{
_messageService = messageService;
}
public string GetMessage()
{
return _messageService.GetMessage();
Đăng nhập để tham gia thảo luận cùng mọi người.
Chưa có bình luận nào
Hãy là người đầu tiên chia sẻ suy nghĩ của bạn.