【问题标题】:ASP.NET 5 DI Connection String into ADO.NETASP.NET 5 DI 连接字符串到 ADO.NET
【发布时间】:2015-08-12 19:41:33
【问题描述】:

早上好,

我们目前正在从 EF 迁移到使用 ADO.NET 作为我们的后端。对于 EF,注入连接字符串非常容易。但是,我无法弄清楚如何使用标准服务来做到这一点。目前的代码是:

services.AddScoped<IDataCatalogRepository, SqlDataCatalogRepository>();

目前正在通过 GitHub 上的依赖注入测试项目,但没有看到我需要的确切内容。我想做的是:

services.AddScoped<IDataCatalogRepository, SqlDataCatalogRepository>("connectionString")

SqlDataCatalogRepository 确实将 connectionString 作为其构造函数属性之一。

使用 Beta 4,有什么想法吗?

史蒂文·M.

【问题讨论】:

标签: dependency-injection asp.net-core


【解决方案1】:

你需要的是一个工厂。您使用的 AddScoped 方法很少有重载,包括带有 implementationFactory 参数的重载。

您的代码将如下所示:

private static readonly Func<IServiceProvider, IDataCatalogRepository> repoFactory = (_) => 
{
    var connectionString = "get your connection string from somewhere";
    return new SqlDataCatalogRepository(connectionString);
}

然后像这样调用 AddScoped:

services.AddScoped<IDataCatalogRepository>(repoFactory);

【讨论】:

  • 正是我要输入的内容!不过,您可以将工厂委托直接传递给 AddScoped 调用,我建议将连接字符串逻辑移出委托以提高效率,具体取决于源。
【解决方案2】:

我刚刚在这里回答了非常相似的问题: https://stackoverflow.com/a/39252582/1905693


我的存储库类中有一个构造函数,它接受 db 连接字符串作为参数。当我添加用于注入的存储库时,这对我有用。在 startup.cs 文件的 ConfigureServies() 中添加:

services.AddScoped<IRepos>(c => new Repos(Configuration["DbConnections:ConnStr1"]));

IRepos.cs 是接口,Repos.cs 是实现它的类。当然,Configuration 只是对构建的 IConfigurationRoot 对象的引用。

【讨论】:

    猜你喜欢
    • 2017-08-18
    • 2015-09-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-26
    • 1970-01-01
    • 2013-06-04
    • 1970-01-01
    • 2019-08-23
    相关资源
    最近更新 更多