gpt4 book ai didi

c# - 在 ConfigureServices 中注入(inject)依赖

转载 作者:行者123 更新时间:2023-11-30 13:54:09 24 4
gpt4 key购买 nike

在我的 ASP.Net Core 应用程序中,我需要在 ConfigureServices 方法中注入(inject)一些依赖项(在我的例子中是一个存储库)。

问题是该方法不允许使用多个参数来注入(inject)依赖项。该怎么做?

这是我的代码

public void ConfigureServices(IServiceCollection services)
{
services.AddOptions();

// ...
services.AddSingleton<ITableRepositories, TableClientOperationsService>();

// Add framework services.
services.AddOpenIdConnect(options =>
{
// options.ClientId = ...
options.Events = new OpenIdConnectEvents
{
OnTicketReceived = async context =>
{
var user = (ClaimsIdentity)context.Principal.Identity;
if (user.IsAuthenticated)
{
// ...
// vvv
// HERE, I need the ITableRepositories repository;
// vvv
var myUser = await repository.GetAsync<Connection>(userId);
// ...
}
return;
}
};
});
}

如何在此处注入(inject)依赖项?

编辑:

按照 Chris 的想法(如下),这似乎可行:

public class Startup
{
// private repository, used in ConfigureServices, initialized in Startup
ITableRepositories repository;

public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
// ... etc etc
Configuration = builder.Build();

// init repository here
this.repository = new TableClientOperationsService();
}

最佳答案

您可以通过当前上下文的HttpContext.RequestServices访问服务容器。

public void ConfigureServices(IServiceCollection services) {
services.AddOptions();

// ...
services.AddSingleton<ITableRepositories, TableClientOperationsService>();

// Add framework services.
services.AddOpenIdConnect(options => {
// options.ClientId = ...
options.Events = new OpenIdConnectEvents {
OnTicketReceived = async context => {
var user = (ClaimsIdentity)context.Principal.Identity;
if (user.IsAuthenticated) {
// ...

// get the ITableRepositories repository
var repository = context.HttpContext.RequestServices.GetService<ITableRepositories>();
var myUser = await repository.GetAsync<Connection>(userId);

// ...
}
return;
}
};
});
}

因此从技术上讲,您不需要访问 ConfigureServices 中的依赖项,因为内联表达式可以提取到它自己的函数中。

public void ConfigureServices(IServiceCollection services) {
services.AddOptions();

// ...
services.AddSingleton<ITableRepositories, TableClientOperationsService>();

// Add framework services.
services.AddOpenIdConnect(options => {
// options.ClientId = ...
options.Events = new OpenIdConnectEvents {
OnTicketReceived = TicketReceived
};
});
}

private async Task TicketReceived(TicketReceivedContext context) {
var user = (ClaimsIdentity)context.Principal.Identity;
if (user.IsAuthenticated) {
// ...

// get the ITableRepositories repository
var repository = context.HttpContext.RequestServices.GetService<ITableRepositories>();
var myUser = await repository.GetAsync<Connection>(userId);

// ...
}
return;
}

关于c# - 在 ConfigureServices 中注入(inject)依赖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46429557/

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