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

How can you create your own Scope for a Scoped object in .NET?

Câu trả lời

In .NET Core, creating your own scope for a scoped object involves using the IServiceScopeFactory to create a new service scope. This is particularly useful when you need to resolve scoped services outside of the typical HTTP request pipeline, such as in background tasks or singleton services. Here’s a step-by-step guide on how to achieve this:

Step-by-Step Guide

  1. Inject IServiceScopeFactory:
    First, ensure that IServiceScopeFactory is injected into the class where you need to create the scope.

    csharp Copy
    public class MyService
    {
        private readonly IServiceScopeFactory _serviceScopeFactory;
    
        public MyService(IServiceScopeFactory serviceScopeFactory)
        {
            _serviceScopeFactory = serviceScopeFactory;
        }
    }
  2. Create a New Scope:
    Use the CreateScope method of IServiceScopeFactory to create a new scope. This scope will be used to resolve scoped services.

    csharp Copy
    public void DoWork()
    {
        using (var scope = _serviceScopeFactory.CreateScope())
        {
            var scopedService = scope.ServiceProvider.GetRequiredService<IMyScopedService>();
            // Use the scoped service
            scopedService.PerformTask();
        } // The scope and all resolved services will be disposed here
    }
  3. Dispose of the Scope:
    Ensure that the scope is properly disposed of after use. This can be done using a using statement, which ensures that the scope is disposed of at the end of the block.

Example Code

Here is a complete example demonstrating how to create and use a scope within a singleton service:

csharp Copy
public interface IMyScopedService
{
    void PerformTask();
}

public class MyScopedService : IMyScopedService
{
    public void PerformTask()
    {
        // Implementation of the task
    }
}

public class MySingletonService
{
    private readonly IServiceScopeFactory _serviceScopeFactory;

    public MySingletonService(IServiceScopeFactory serviceScopeFactory)
    {
        _serviceScopeFactory = serviceScopeFactory;
    }

    public void Execute()
    {
        using (var scope = _serviceScopeFactory.CreateScope())
        {
            var scopedService = scope.ServiceProvider.GetRequiredService<IMyScopedService>();
            scopedService.PerformTask();
        }
    }
}

// In Startup.cs or Program.cs
public void ConfigureServices(IServiceCollection services)
{
    services.AddScoped<IMyScopedService, MyScopedService>();
    services.AddSingleton<MySingletonService>();
}

Explanation

  • **Inject...
middle

middle

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

entry

What is the difference between String and string in C#?

junior

What is a .NET application domain?

junior

Name some CLR services?

Bình luận

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

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