2017-09-01 33 views
2

私はASP.NET Coreアプリケーションで一般的なDIの使用法を使用しています。 ConfigContextASP.NETコアのDIで初期化オブジェクトからオブジェクトを初期化

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

UserContextconnectionStringを返すメソッドGetUserStringが存在します。 UserContextにお申込みの場合、AddScoped UserContextconnectionStringConfigContext が必要です。

+0

接続文字列はリクエストごとに異なる場合があります(別のユーザー)。 –

+0

はい、configcontextのロジックによって異なる場合があります –

答えて

2

サービスを実装ファクトリに登録し、引数として提供されたIServiceProviderを使用して、ファクトリ内の別のサービスを解決することができます。

このように、1つのサービスを使用して別のサービスをインスタンス化することができます。

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())); 
} 
関連する問題