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

Ste*_*yer 2 dependency-injection asp.net-core

早上好,

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

services.AddScoped<IDataCatalogRepository, SqlDataCatalogRepository>();
Run Code Online (Sandbox Code Playgroud)

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

services.AddScoped<IDataCatalogRepository, SqlDataCatalogRepository>("connectionString")
Run Code Online (Sandbox Code Playgroud)

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

使用Beta 4,任何想法?

史蒂文先生

Mar*_* M. 7

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

您的代码看起来像这样:

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

然后像这样调用AddScoped:

services.AddScoped<IDataCatalogRepository>(repoFactory);
Run Code Online (Sandbox Code Playgroud)