2017-09-01 149 views
2

在我的ASP.NET Core应用程序中有常见的DI用法。在ASP.NET Core中使用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));   
} 

ConfigContext存在方法GetUserString它返回到connectionStringUserContext。 而我需要AddScoped UserContextconnectionStringConfigContext 当适用于UserContext时。

+0

连接字符串可以根据每个请求(不同的用户)而变化吗? –

+0

是的,可以根据configcontext中的逻辑而有所不同 –

回答

2

您可以使用实现工厂注册服务,并使用提供的IServiceProvider作为参数来解析工厂内的其他服务。

以这种方式,您正在使用一种服务来帮助实例化另一种服务。

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