【问题标题】:Resolve scoped service from singleton service从单例服务解析范围服务
【发布时间】:2020-08-05 11:22:30
【问题描述】:

是否有可能在一个单例服务的方法中解析一个作用域服务,该方法被一个作用域服务调用?

例如我有一个单例服务“GlobalService”和一个范围内的“UserService”。

如果 UserService 在“GlobalService”中执行方法“Job”,是否可以通过使用 Assembly.GetCallingAssembly() 在此方法中获取范围服务?否则我需要传递所有必需的参数。

谢谢你✌

【问题讨论】:

    标签: asp.net-core


    【解决方案1】:

    Singleton 将只有一个实例,可供您的作用域服务使用。您的作用域服务方法可以使用单例服务实例。

    如果调用单例服务的方法,则可以在其中获取作用域服务对象。您可以使用 IHttpcontextAccessor 来解析该方法内的作用域服务实例。

    internal class Singleton
    {
        private readonly IHttpContextAccessor httpContextAccessor;
    
        public Singleton(IHttpContextAccessor httpContextAccessor)
        {
            this.httpContextAccessor = httpContextAccessor;
        }
        public int Job()
        {
            return httpContextAccessor.HttpContext.RequestServices.GetRequiredService<Scoped>().MyProperty;
        }
    }
    

    您需要在 Startup 的 ConfigureServices 方法中注册这些服务:

    services.AddHttpContextAccessor();
    services.AddScoped<Scoped>();
    services.AddSingleton<Singleton>();
    

    【讨论】:

    • 所以我至少需要 IHttpContextAccessor 作为参数?这是我目前的解决方案 - 我想删除它。你能给我打一些伪代码吗?
    • 你需要 IHttpContextAccessor 来访问单例服务方法中的作用域服务实例,我知道没有其他方法。
    • 好的,谢谢。因此,由于 IHttpContextAccessor 的范围是每个定义,我需要在方法 Job 中传递它?例如。无效作业(IHttpContextAccessor 上下文){}
    • 非常感谢! :)
    • 非常感谢! :) 我懂了!不知道 IHttpContextAccessor 在单例中可用!非常感谢!杰出的! :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-04
    • 2018-09-27
    • 1970-01-01
    • 1970-01-01
    • 2019-07-02
    • 2018-04-04
    • 1970-01-01
    相关资源
    最近更新 更多