【问题标题】:Getting Instance Of Service in Configure Services (Not by services.BuildServiceProvider())在配置服务中获取服务实例(不是通过 services.BuildServiceProvider())
【发布时间】:2021-12-01 13:08:14
【问题描述】:

我正在实现一个自定义票证存储并将身份验证令牌存储在数据库中,而不是 cookie。

作为其中的一部分,我创建了一个 CustomTicketStore 并像这样注入

services.AddSingleton<ITicketStore, CustomTicketStore>();

在 Startup.cs 中,我需要访问此 CustomTicketStore 的实例

当我添加 cookie 时

.AddCookie("Cookies", o =>
            {
                // TODO: Have to fix this (not use BuildServiceProvider)
                var sp = services.BuildServiceProvider();
                var ticketStoreService = sp.GetService<ITicketStore>();
                o.SessionStore = ticketStoreService;

但后来我收到了来自 Microsoft 的警告

这是一个替代但丑陋的

//o.SessionStore = new CustomTicketStore(new AuthRepository(() => 
                //    new OracleConnection(connection_details);

还有其他方法可以使用注入的服务吗?

【问题讨论】:

  • 没有评论的-1,太棒了
  • this blog可以帮到你吗?

标签: asp.net asp.net-core .net-core dependency-injection


【解决方案1】:

由于您在配置服务方法中调用服务,并且该方法只能注入 IServiceCollection 并且您想在 AddCookie 方法中设置一些存储。

所以没有其他方法可以在 Action 中获取注册的服务。

【讨论】:

    猜你喜欢
    • 2019-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-31
    • 1970-01-01
    • 2012-02-08
    • 1970-01-01
    相关资源
    最近更新 更多