Dependency injection ASP.NET 5 DI连接字符串转换为ADO.NET
早上好 我们目前正在从EF迁移到后端使用ADO.NET。对于EF,注入连接字符串非常容易。但是,我不知道如何使用标准服务来实现这一点。目前的代码是:Dependency injection ASP.NET 5 DI连接字符串转换为ADO.NET,dependency-injection,asp.net-core,Dependency Injection,Asp.net Core,早上好 我们目前正在从EF迁移到后端使用ADO.NET。对于EF,注入连接字符串非常容易。但是,我不知道如何使用标准服务来实现这一点。目前的代码是: services.AddScoped<IDataCatalogRepository, SqlDataCatalogRepository>(); services.addScope(); 目前正在GitHub上进行依赖项注入测试项目,但没有看到我需要的东西。我想做的是: services.AddScoped<IDataCatal
services.AddScoped<IDataCatalogRepository, SqlDataCatalogRepository>();
services.addScope();
目前正在GitHub上进行依赖项注入测试项目,但没有看到我需要的东西。我想做的是:
services.AddScoped<IDataCatalogRepository, SqlDataCatalogRepository>("connectionString")
services.AddScoped(“connectionString”)
SqlDataCatalogRepository确实将connectionString作为其构造函数属性之一
使用Beta 4,有什么想法吗
Steven M.你需要的是一个工厂。您使用的AddScope方法很少有重载,包括带有implementationFactory参数的重载 您的代码如下所示:
private static readonly Func repoFactory=(\u)=>
{
var connectionString=“从某处获取连接字符串”;
返回新的SqlDataCatalogRepository(connectionString);
}
然后像这样调用addScope:
services.AddScoped(repoFactory);
我刚才回答了一个非常类似的问题:
我的repository类中有一个构造函数,它接受db连接字符串作为参数。当我添加用于注入的存储库时,这对我很有效。在startup.cs文件的ConfigureServices()中添加以下内容:
services.AddScoped<IRepos>(c => new Repos(Configuration["DbConnections:ConnStr1"]));
services.AddScoped(c=>newrepos(配置[“DbConnections:ConnStr1]”);
IRepos.cs是接口,Repos.cs是实现它的类。当然,配置只是对内置IConfigurationRoot对象的引用。您可以使用
选项?这正是我要打的!不过,您可以将工厂委托直接传递给addScope调用,我建议将连接字符串逻辑移出委托,以提高效率,具体取决于源。
services.AddScoped<IDataCatalogRepository>(repoFactory);
services.AddScoped<IRepos>(c => new Repos(Configuration["DbConnections:ConnStr1"]));