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

What is the difference between IHost...

Câu trả lời

In .NET Core, IHost, IHostBuilder, and IHostedService are key components used for building and managing applications, particularly those that require background processing or complex initialization. Here’s a detailed explanation of the differences between them:

IHost

IHost is an interface that represents the host for an application. It encapsulates all the resources needed to run the application, such as dependency injection (DI), configuration, and logging. The IHost interface provides methods to start and stop the application and manage its lifecycle.

Key Features:

  • Dependency Injection: Manages the lifetime of services.
  • Configuration: Loads configuration settings.
  • Logging: Provides logging capabilities.
  • Application Lifetime: Manages the application’s start and stop events.

Example:

csharp Copy
public static async Task Main(string[] args)
{
    var host = Host.CreateDefaultBuilder(args)
                   .ConfigureServices((context, services) =>
                   {
                       services.AddHostedService<MyBackgroundService>();
                   })
                   .Build();

    await host.RunAsync();
}

In this example, Host.CreateDefaultBuilder sets up the default configuration and services, and Build creates the IHost instance which is then run asynchronously.

IHostBuilder

IHostBuilder is an interface used to configure and create an IHost instance. It provides methods to set up the host configuration, add services to the DI container, and configure logging. Essentially, IHostBuilder is used during the application startup to build the IHost.

Key Features:

  • Configuration: Allows adding configuration sources.
  • Service Registration: Adds services to the DI container.
  • Logging Configuration: Configures logging providers.
  • Host Options: Configures options related to the host, such as shutdown timeout.

Example:

csharp Copy
public static IHostBuilder ...
senior

senior

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

junior

What is .NET Standard and why we need to consider it?

senior

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

middle

What's is BCL?

Bình luận

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

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