2

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.

2
  • Can the connection string vary on a per-request basis (different user)? Commented Sep 1, 2017 at 15:46
  • Yes, can differ depending on the logic in the configcontext Commented Sep 1, 2017 at 18:33

1 Answer 1

2

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()));
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.