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 ?
Using field injection we can inject dependencies by setting field values on your classes directly, even on private fields, with the help of Java technology called Reflection. To use field injection, we have to configure the dependency injection with autowired annotation, with no need for setter methods.
The 4 roles in dependency injectionThe service you want to use. The client that uses the service. An interface that's used by the client and implemented by the service. The injector which creates a service instance and injects it into the client.
Dependency Injection (DI) is a design pattern used to implement IoC. It allows the creation of dependent objects outside of a class and provides those objects to a class through different ways. Using DI, we move the creation and binding of the dependent objects outside of the class that depends on them.
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) { ... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With