【问题标题】:Consume Dependencies from the Startup从启动中使用依赖项
【发布时间】:2017-08-16 19:34:11
【问题描述】:

我想知道在启动类中使用依赖项的正确方法是什么?

我已经配置了我的应用程序并在服务中添加了一个上下文

public void ConfigureServices(IServiceCollection services)
{
    services.AddEntityFramework().AddDbContext<ApplicationContext>(options => 
                                         options.UseSqlServer(connection));
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    app.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions
    {
        Authority = "https://localhost:4430",
        RequireHttpsMetadata = false,

        ApiName = "api",
        JwtBearerEvents = new SyncUserBearerEvent()
        {
            OnTokenValidated = async tokenValidationContext =>
            {

                    var claimsIdentity = tokenValidationContext.Ticket.Principal.Identity as ClaimsIdentity;
                    if (claimsIdentity != null)
                    {
                        // Get the user's ID
                        string userId = claimsIdentity.Claims.FirstOrDefault(c => c.Type == "sub").Value;

                    }

                    //I need to spawn a context here

                }
            }
        }
    });
}

我需要在接下来调用的 configure 方法中使用这个上下文。我读过一些创建新 DbContext 的文章,但不正确,应该从我们的服务中使用。

在启动方法中使用新的 Db 上下文的正确方法是什么?

【问题讨论】:

    标签: c# entity-framework dependency-injection asp.net-core


    【解决方案1】:

    在 ConfigureServices 方法调用完成后,在 ConfigureServices 方法中注册的依赖项就可以使用了。由于 Configure 方法是在 ConfigureServices 之后触发的,因此可以使用参数注入在 Configure 方法中使用注册的依赖项,而不是在方法内部更新它们。如果你只需要一个单例,你可以在 Configure 方法中注入服务,如下所示。

    public void Configure(IApplicationBuilder app, 
                          IHostingEnvironment env, 
                          ILoggerFactory loggerFactory,
                          IDependentService service)
    {
          //You can use dbContext here.
    }
    

    您还可以像这样从应用服务中生成上下文:

    var dependentService = app.ApplicationServices.GetRequiredService<IDependentService>())
    

    如果您需要一个 dbContext,您将需要通过 HttpContext 访问服务提供。在您的实例中,您可以通过传入的 TokenValidatedContext 访问它,如下所示:

    var serviceProvider = tokenValidationContext.HttpContext.RequestServices;
    using (var context = serviceProvider.GetRequiredService<AstootContext>())
    {
    }
    

    【讨论】:

    • 想解释一下为什么以及如何?
    • 有趣,我需要验证这是否有效,但这在 OnTokenValidated 方法中使用,如上所示,并且我希望我的上下文在应用程序的整个生命周期中都不打开,
    • @johnny5 : AddDbContext 的第三个参数是 ServiceLifetime,其默认值为“Scoped”,所以我相信您的上下文不会在应用程序生命周期内打开。
    • @PankajKapare Configure 只被调用一次,所以在这里改变生命周期工作
    • @johnny5: 是的,配置,ConfigureServices 方法仅在构建 WebHost 时调用一次。
    猜你喜欢
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-12
    • 2021-12-07
    • 1970-01-01
    • 2011-06-20
    • 1970-01-01
    相关资源
    最近更新 更多