Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inject dependency in the 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 ?

Here is my code

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?

EDIT:

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();
    }
like image 992
serge Avatar asked Sep 26 '17 14:09

serge


People also ask

How can we inject the service dependency into the controller?

How can we inject the service dependency into the controller C# Asp.net Core? ASP.NET Core injects objects of dependency classes through constructor or method by using built-in IoC container. The built-in container is represented by IServiceProvider implementation that supports constructor injection by default.

What is dependency injection in NET Core?

ASP.NET Core supports the dependency injection (DI) software design pattern, which is a technique for achieving Inversion of Control (IoC) between classes and their dependencies. For more information specific to dependency injection within MVC controllers, see Dependency injection into controllers in ASP.NET Core.


1 Answers

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

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;
}
like image 168
Nkosi Avatar answered Oct 06 '22 23:10

Nkosi