serge
serge

Reputation: 15239

using DependencyInjection in the Configure Method

In an ASP.NET CORE web application, I have a MyRepository class and an Interface IMyRepository that manages the access to the repository (database).

Each time a user connects to the application(on the site), I need to log an entry in the database.

In Startup.cs, in the ConfigureServices method I do

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

Then in the Configure method I need to update the database

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

// ...

}

So my question is how/where do I inject the IMyRepository for use it in that Configure method ?

Upvotes: 6

Views: 1707

Answers (1)

Ricardo Peres
Ricardo Peres

Reputation: 14555

Modify your Configure method to take an additional parameter IMyRepository myRep, it will be injected for you as long as you register it in ConfigureServices.

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

Upvotes: 7

Related Questions