【问题标题】:using DependencyInjection in the Configure Method在配置方法中使用 DependencyInjection
【发布时间】:2018-01-30 23:50:51
【问题描述】:

在 ASP.NET CORE Web 应用程序中,我有一个 MyRepository 类和一个接口 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);
        }
    }
});

// ...

}

所以我的问题是如何/在哪里注入 IMyRepository 以便在 Configure 方法中使用它?

【问题讨论】:

    标签: c# asp.net dependency-injection asp.net-core-mvc asp.net-core-1.1


    【解决方案1】:

    修改你的Configure方法,增加一个参数IMyRepository myRep,只要你在ConfigureServices注册它就会为你注入。

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

    【讨论】:

    • 是的,因为我认为ConfigureServices 方法在Configure 之前首先运行
    • 这么简单?! :) 如果 OnTicketsRecieved 是在 Configure 方法之外定义的函数怎么办?
    • @SergeI 我认为你必须使用构造函数注入并将IMyRepository 的实例传递给你的构造函数。例如在控制器中。
    • 嗯...实际上我不知道如何将“已连接事件”链接到控制器的操作的问题...我已经在控制器中使用了构造函数注入,但这次我没有不知道如何在控制器中移动该代码...
    • 谢谢,您的解决方案帮助了我。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多