Câu hỏi phỏng vấn .NET Core
Câu hỏi

What is IoC (DI) Container?

Câu trả lời

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.

Key Features of IoC (DI) Container in .NET Core

  1. 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].

  2. 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].

  3. Lifecycle Management: The IoC container manages the lifecycle of the services it creates. .NET Core supports three main service lifetimes:

    • Singleton: A single instance of the service is created and shared throughout the application's lifetime.
    • Scoped: A new instance of the service is created per request.
    • Transient: A new instance of the service is created each time it is requested[1][2][3][7].

Benefits of Using IoC (DI) Container

  • Loose Coupling: Classes do not need to know how their dependencies are created, promoting modularity and flexibility.
  • Testability: Dependencies can be easily mocked or stubbed, making unit testing simpler.
  • Maintainability: Changes to dependencies do not require changes to the classes that use them, as long as the interface remains the same.
  • Configuration Management: Dependencies are configured in a central location, making it easier ...
junior

junior

Gợi ý câu hỏi phỏng vấn

senior

Why shouldn't I use the Repository Pattern with Entity Framework?

senior

What is the difference between CIL and MSIL (IL)?

middle

What is JIT compiler?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào