如何在单例中使用作用域依赖注入 [英] How to use scoped dependency injection in singleton

查看:18
本文介绍了如何在单例中使用作用域依赖注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个范围服务(让它成为包含用户 IP 的 UserContext).它服务我尝试注入另一个服务(让我们称它们为 ProfileManagerLogerProvider).

I have a scoped service (lets it be UserContext, that contain user IP). It service I try to inject in another services (let's call them ProfileManager and LogerProvider).

在我启动时的控制器中,我像这样添加它们:

In my controller at startup, I added them like so:

service
   .AddTransient(ILogerProvider, LogerProvider)()
   .AddSingleton<IProfileManager, ProfileManager)()
   .AddScoped<IUserContext, UserContext>()

Class LogerProvider 包含 UserContext 注入:

Class LogerProvider contain UserContext inject:

class LogerProvider: ILogerProvider
{
   private readonly IUserContext _userContext;

   public LogerProvider(IUserContext userContext)
   {
      _userContext = userContext;
   }
}

Class ProfileManager 包含 LogerProvider 注入:

Class ProfileManager contain LogerProvider inject:

class ProfileManager: IProfileManager
{
   private readonly ILogerProvider _logerProvider;

   public ProfileManager(ILogerProvider logerProvider)
   {
      _logerProvider = logerProvider;
   }
}

当我尝试运行我的程序时出现错误:

And when i try to run my program i got error:

(Inner Exception #1) System.InvalidOperationException: Error while validating the service descriptor 'ServiceType: IProfileManager Lifetime: Singleton ImplementationType: IProfileManager': Cannot consume scoped service 'IUserContext' from singleton 'IProfileManager'.

我发现我可以改变 ProfileManager 的生命周期,让它成为瞬态.但我需要像单身人士一样使用这项服务.所以一个问题:我如何实现依赖注入保存了服务的生命周期我在文本的开头是如何输入的?

I found that i can just change lifetime of ProfileManager just make it transient. But i need to use this service like singleton. So a question: how i can realize dependency injection saved lifetime of services how i typed at the beginning of the text?

推荐答案

您需要手动创建一个范围并使用它,为此您需要将 IServiceProvider 注入到您的单例服务中然后调用 IServiceCollection.CreateScope

You need to manually create a scope and consume it, to do so you'll need to inject the IServiceProvider into your singleton service and then call IServiceCollection.CreateScope

public class ProfileManager : IProfileManager
{
    private readonly IServiceProvider _services;

    public ProfileManager(IServiceProvider services)
    {
        _services = services;
    }

    public void DoSomething()
    {
        using (var scope = _services.CreateScope())
        {
            var logger = scope.ServiceProvider.GetRequiredService<ILogerProvider>();
        }
    }
}

旁注:如果您发现自己一次又一次地重复这种模式,您可能需要重新考虑服务的生命周期和范围

Sidenote: You may want to rethink the lifetimes and scopes of your services if you find yourself repeating this pattern again and again

这篇关于如何在单例中使用作用域依赖注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆