gpt4 book ai didi

c# - 在 Configure 方法中使用 DependencyInjection

转载 作者:行者123 更新时间:2023-11-30 15:17:39 26 4
gpt4 key购买 nike

在 ASP.NET CORE Web 应用程序中,我有一个 MyRepository 类和一个管理对存储库(数据库)的访问的接口(interface) IMyRepository

每次用户连接到应用程序(在站点上)时,我都需要在数据库中记录一个条目。

在 Startup.cs 中,我在 ConfigureServices 方法中执行

public void ConfigureServices(IServiceCollection services)
{
// Adds services required for using options.
services.AddOptions();
// ...
services.AddSingleton<IMyRepository, MyRepository>();

然后在Configure方法中我需要更新数据库

public void Configure(IApplicationBuilder app, 
IHostingEnvironment env, ILoggerFactory loggerFactory) {
// ...
IMyRepository myRep = ??? // should inject somehow
// ...

app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions
{
ClientId = Configuration["...ClientId"],
Authority = Configuration["...AADInstance"] + Configuration["...TenantId"],
CallbackPath = Configuration["...CallbackPath"],
Events = new OpenIdConnectEvents
{
OnTicketReceived = context =>
{
var user = (ClaimsIdentity)context.Ticket.Principal.Identity;
if (user.IsAuthenticated)
{
var firstName = user.FindFirst(ClaimTypes.GivenName).Value;
var lastName = user.FindFirst(ClaimTypes.Surname).Value;
var email = user.FindFirst(ClaimTypes.Email).Value;
var connectedOn = DateTime.UtcNow;
var userId = user.Name;

//
// HERE ADD the info in the DB via IMyRepository
//
myRep.AddUserInfo(userId, firstName, lastName, email, connectedOn);
}

return Task.FromResult(0);
}
}
});

// ...

}

所以我的问题是如何/在何处注入(inject) IMyRepository 以便在 Configure 方法中使用它?

最佳答案

修改您的Configure 方法以获取一个额外的参数IMyRepository myRep,只要您在ConfigureServices 中注册它就会为您注入(inject).

public void Configure(IApplicationBuilder app, 
IHostingEnvironment env,
ILoggerFactory loggerFactory,
IMyRepository myRep) { ... }

关于c# - 在 Configure 方法中使用 DependencyInjection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45821930/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com