ASP.NET 5 DI连接字符串到ADO.NET

时间:2015-05-29 19:55:55

标签: dependency-injection asp.net-core

早上好,

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

services.AddScoped<IDataCatalogRepository, SqlDataCatalogRepository>();

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

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

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

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

Steven M。

2 个答案:

答案 0 :(得分:7)

您需要的是工厂。您使用的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);

答案 1 :(得分:1)

我刚才回答了一些非常类似的事情: https://stackoverflow.com/a/39252582/1905693

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

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

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