Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/entity-framework/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用启动时的依赖项_C#_Entity Framework_Dependency Injection_Asp.net Core - Fatal编程技术网

C# 使用启动时的依赖项

C# 使用启动时的依赖项,c#,entity-framework,dependency-injection,asp.net-core,C#,Entity Framework,Dependency Injection,Asp.net Core,我想知道在启动类中使用依赖项的正确方法是什么 我已经配置了应用程序并在服务中添加了上下文 public void ConfigureServices(IServiceCollection services) { services.AddEntityFramework().AddDbContext<ApplicationContext>(options => options.UseSqlS

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

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

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

                }
            }
        }
    });
}
public void配置服务(IServiceCollection服务)
{
services.AddEntityFramework().AddDbContext(选项=>
选项。使用SQLServer(连接));
}
公共void配置(IApplicationBuilder应用程序、IHostingEnvironment环境、iLogger工厂)
{
app.UseIdentityServerAuthentication(新的IdentityServerAuthenticationOptions
{
权威=”https://localhost:4430",
RequireHttpsMetadata=false,
ApiName=“api”,
JWTBeareEvents=新的SyncUserBeareEvent()
{
OnTokenValidated=异步令牌验证上下文=>
{
var claimsIdentity=tokenValidationContext.Ticket.Principal.Identity作为claimsIdentity;
if(claimsIdentity!=null)
{
//获取用户的ID
字符串userId=claimsIdentity.Claims.FirstOrDefault(c=>c.Type==“sub”).Value;
}
//我需要在这里生成一个上下文
}
}
}
});
}
我需要在下一步调用的configure方法中使用这个上下文。我读过一些文章,认为创建一个新的DbContext是不合适的,应该从我们的服务中使用它


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

在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>())
var dependentService=app.ApplicationServices.GetRequiredService())
如果需要dbContext,则需要通过HttpContext访问提供的服务。在您的实例中,您可以通过传入的TokenValidatedContext访问它,如下所示:

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

想解释原因和方式吗?有趣的是,我需要验证这是否有效,但如上所述,这是在OnTokenValidated方法中使用的,我希望我的上下文在应用程序的整个生命周期内都不会打开,@johnny5:AddDbContext的第三个参数是ServiceLifetime,其默认值为“Scoped”所以我相信您的上下文在应用程序生命周期内不会打开。@PankajKapare配置只调用一次,所以更改生命周期是可行的here@johnny5:Yes Configure,在生成WebHost时只调用一次ConfigureServices方法。