How to Create Your Own Scope for a Scoped Object in .NET Core

πŸ’‘ Concept Name

Manual Scope Creation for Scoped Services in .NET Core

πŸ“˜ Quick Intro

In .NET Core, scoped services are typically created per HTTP request. But if you're outside the request pipelineβ€”like in background jobsβ€”you can create your own custom scope using IServiceScopeFactory.

🧠 Analogy / Short Story

Imagine you're in a hotel where every guest gets a unique room key that works only for their stay (scope). If you need to give someone access without checking them in, you create a temporary key (custom scope) that works only for that moment.

πŸ”§ Technical Explanation

Use IServiceScopeFactory.CreateScope() to manually generate a new DI scope. Inside this scope, you can resolve any scoped service using the scope’s ServiceProvider. Once disposed, all scoped services within it are cleaned up properly.

🎯 Purpose & Use Case

  • βœ… Using scoped services in background tasks
  • βœ… Accessing scoped services in hosted services
  • βœ… Triggering scoped logic from console apps
  • βœ… Avoiding memory leaks by properly disposing scopes

πŸ’» Real Code Example

Creating a Custom Scope in a Background Task:

public class MyWorker
{
    private readonly IServiceScopeFactory _scopeFactory;

    public MyWorker(IServiceScopeFactory scopeFactory)
    {
        _scopeFactory = scopeFactory;
    }

    public async Task RunAsync()
    {
        using (var scope = _scopeFactory.CreateScope())
        {
            var scopedService = scope.ServiceProvider.GetRequiredService<IMyScopedService>();
            await scopedService.DoWorkAsync();
        }
    }
}

❓ Interview Q&A

Q1: Why would you create a custom scope in .NET Core?
A: To use scoped services outside of the HTTP request pipeline.

Q2: Which interface is used to create a new scope?
A: IServiceScopeFactory

Q3: How do you properly dispose of scoped services manually?
A: Wrap the scope in a using block to auto-dispose.

Q4: Where is this commonly used?
A: In background services, console apps, or startup logic.

Q5: What happens if you resolve a scoped service from root provider?
A: It may lead to incorrect lifetimes or memory leaks.

Q6: Can you use IOptionsSnapshot inside a custom scope?
A: Yes, as it's scoped per request or per scope.

Q7: What is the lifetime of a scoped object created using CreateScope?
A: It lasts until the scope is disposed.

Q8: Is it thread-safe to use the same scope in multiple threads?
A: No, each thread should use its own scope.

Q9: Can singleton services resolve scoped services?
A: Only by creating a new scope manually.

Q10: How do you inject IServiceScopeFactory?
A: Via constructor using dependency injection.

πŸ“ MCQs

Q1. What is the correct interface to manually create a scope?

  • IServiceProvider
  • IServiceCollection
  • IServiceScopeFactory
  • IHostApplicationLifetime

Q2. Why create a scope manually in .NET Core?

  • To increase performance
  • To use scoped services outside of HTTP pipeline
  • To override services
  • To avoid DI completely

Q3. What ensures disposal of scoped services?

  • GC
  • Manual clear
  • using block with CreateScope()
  • Restarting app

Q4. What method is used to create a scope?

  • GetScope()
  • NewScope()
  • CreateScope()
  • InitScope()

Q5. Can you resolve scoped services using root provider?

  • Yes
  • Only in Startup
  • No, it may lead to lifetime issues
  • Only with Transient

Q6. What is injected to create a custom scope?

  • IHost
  • IConfiguration
  • ILogger
  • IServiceScopeFactory

Q7. What is a real-world use of custom scope?

  • CSS injection
  • JavaScript injection
  • Background services
  • UI rendering

Q8. What is the default lifetime of services in .NET Core?

  • Singleton
  • Scoped
  • Transient
  • Global

Q9. What happens if scope is not disposed?

  • Nothing
  • Faster performance
  • Memory leaks may occur
  • Auto-cleaned on compile

Q10. Can you use IOptionsMonitor in a custom scope?

  • No
  • Only in Startup
  • Yes
  • Only in Middleware

πŸ’‘ Bonus Insight

Manually creating scopes is powerfulβ€”but use it sparingly. Always use `using` blocks to avoid memory leaks. Consider using HostedService with scoped factory when integrating long-running tasks.

πŸ“„ PDF Download

Need a handy summary for your notes? Download this topic as a PDF!

πŸ’¬ Feedback
πŸš€ Start Learning
Share:

Tags: