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
[1][2][3][4].
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();
}
}
Here, MyClass
depends on IMessageService
, and the IoC container provides an instance of MessageService
when MyClass
is instantiated[2][5][6].
Lifecycle Management: The IoC container manages the lifecycle of the services it creates. .NET Core supports three main service lifetimes:
junior
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào