【问题标题】:Initialize object from Initialized object by DI in ASP.NET Core在 ASP.NET Core 中通过 DI 初始化对象初始化对象
【发布时间】:2018-02-10 17:03:32
【问题描述】:

我的 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,它将connectionString 返回到UserContext。 我需要AddScoped UserContext 和connectionString 来自ConfigContext 申请时UserContext。

【问题讨论】:

  • 连接字符串可以根据每个请求(不同的用户)而变化吗?
  • 是的,可以根据配置上下文中的逻辑而有所不同

标签: c# dependency-injection asp.net-core asp.net-core-mvc


【解决方案1】:

您可以向实现工厂注册服务,并使用作为参数提供的 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()));
}

【讨论】:

    猜你喜欢
    • 2013-06-27
    • 1970-01-01
    • 1970-01-01
    • 2013-05-07
    • 1970-01-01
    • 2012-10-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多