在ConfigureServices中注入依赖项 [英] Inject dependency in the ConfigureServices

查看:168
本文介绍了在ConfigureServices中注入依赖项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的ASP.Net Core应用程序中,我需要在 ConfigureServices 方法中注入一些依赖项(在我的情况下为存储库).

In my ASP.Net Core application I need to inject some dependencies (a repository, in my case) in the ConfigureServices method.

问题在于该方法不允许使用多个参数来注入依赖项.该怎么做呢?

The problem is that method does not allow the use of multiple arguments to inject dependencies. What to do instead ?

这是我的代码

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;
            }
        };
    });
}

如何在此处注入依赖项?

How can I inject the dependency here?

遵循克里斯的想法(贝洛),这似乎行得通:

Following the Chris idea (bellow), that seem to work:

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 访问服务容器.

You can access the service container via the HttpContext.RequestServices of the current context.

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 中的依赖项,因为可以将内联表达式提取到其自己的函数中.

So technically you don't need access to the dependency within the ConfigureServices as the inline expression could be extracted into its own function.

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;
}

这篇关于在ConfigureServices中注入依赖项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆