一旦它被ASP NET Core的DI注入到mvc控制器上,我怎么能解决UserRepo
上的连接字符串依赖性?请注意,我的仓库针对的是.NET 4.6。并使用sql db和dapper orm。提示和建议都可以。
继承代码。
要依赖的界面
public interface IUserRepo
{
List<User> GetAll();
}
将注入mvc控制器并具有自己的依赖项的具体类
public class UserRepo: IUserRepo
{
private string connectionString = "";
//Depends on a connectionstring
public UserRepo(string connectionString)
{
this.connectionString = connectionString;
}
public List<User> GetAll()
{
//create an sqlconnection using provided connectionstring
//return list from db...
}
}
在ASP MVC CORE的startup.cs
上public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
//inject UserRepo , how to resolve UserRepo's dependency?
services.AddScoped<IUserRepo, UserRepo>();
}
答案 0 :(得分:4)
您应该使用接受委托的AddScoped
重载:
services.AddScoped<IAccountRepo>(c => new AccountRepo("constr"));
答案 1 :(得分:0)
如果你有这样的配置设置(appsettings.json
):
{
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet-WebApplication1-26e8893e-d7c0-4fc6-8aab-29b59971d622;Trusted_Connection=True;MultipleActiveResultSets=true"
},
}
你的Startup.cs:
private readonly IConfigurationRoot _configuration;
public Startup(IHostingEnvironment env)
{
_configuration = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile($"appsettings.json", optional:false, reloadOnChange:true)
.Build();
}
public void ConfigureServices(IServiceCollection services)
{
...
services.AddSingleton<IConfiguration>(provider => _configuration);
...
}
然后您可以轻松地在UserRepo上解决它:
public class UserRepo: IUserRepo
{
private readonly string connectionString;
public UserRepo(IConfiguration configuration)
{
this.connectionString = configuration.GetConnectionString("DefaultConnection");;
}
public List<User> GetAll()
{
//create an sqlconnection using provided connectionstring
//return list from db...
}
}