E. Otrokov
E. Otrokov

Reputation: 23

Initialize object from Initialized object by DI in ASP.NET Core

I have common DI usage in my ASP.NET Core application.

public void ConfigureServices(IServiceCollection services)
{  
     services.AddScoped(sp => new UserContext(new DbContextOptionsBuilder().UseNpgsql(configuration["User"]).Options));
     services.AddScoped(sp => new ConfigContext(new DbContextOptionsBuilder().UseNpgsql(configuration["Config"]).Options));         
}

In ConfigContext exists method GetUserString which returns connectionString to UserContext. And I need AddScoped UserContext with connectionString from ConfigContext when applying to UserContext.

Upvotes: 2

Views: 2776

Answers (1)

Mathieu Renda
Mathieu Renda

Reputation: 15336

You can register the service with an implementation factory, and resolve another service inside the factory, using the IServiceProvider provided as an argument.

In this way, you are using one service to help instantiate another.

public class UserContext
{
    public UserContext(string config)
    {
        // config used here
    }
}

public class ConfigContext
{
    public string GetConfig()
    {
        return "config";
    }
}

public void ConfigureServices(IServiceCollection services)
{
    // ...

    services.AddScoped<ConfigContext>();

    services.AddScoped<UserContext>(sp => 
        new UserContext(sp.GetService<ConfigContext>().GetConfig()));
}

Upvotes: 2

Related Questions