以下是我的应用程序如何调用数据库: Web App - >业务层 - >数据层
一切都在使用依赖注入。
例如:
在我的网络应用程序的控制器中,我打这样的电话:
await _manager.GetCustomers();
进入我的业务层:
public class CustomerManager : ICustomerManager
{
private ICustomerRepo _repository;
public CustomerManager(ICustomerRepo repository)
{
_repository = repository;
}
public Task<IList<Customer>> GetCustomers(string name = null)
{
return _repository.GetCustomers(name);
}
}
哪个进入我的数据层:
public class CustomerRepo : BaseRepo, ICustomerRepo
{
public CustomerRepo(IConfigurationRoot configRoot)
: base(configRoot)
{
}
public Customer Find(int id)
{
using (var connection = GetOpenConnection())
{
...
}
}
}
这里的技巧是CustomerRepo继承自BaseRepo以便能够使用GetOpenConnection()函数。但同时BaseRepo需要从Web应用程序注入IConfigurationRoot。我怎么能两个都做?
public class BaseRepo
{
private readonly IConfigurationRoot config;
public BaseRepo(IConfigurationRoot config)
{
this.config = config;
}
public SqlConnection GetOpenConnection(bool mars = false)
{
string cs = config.GetSection("Data:DefaultConnection:ConnectionString").ToString();
...
}
}
答案 0 :(得分:4)
无论依赖注入如何,您将如何实例化(甚至编译)CustomerRepo?您需要IConfigurationRoot
参数才能传递给基础构造函数。像:
public CustomerRepo(IConfigurationRoot configRoot)
: base(configRoot)
{
}
有关基本关键字的信息,请参阅https://msdn.microsoft.com/en-us/library/hfw7t1ce.aspx。