这是我的应用程序调用数据库的方式:Web应用程序->业务层->数据层
一切都在使用依赖注入。
例如:
在我的Web应用程序的控制器中,我进行如下调用:
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();
...
}
}
无论依赖项注入如何,您将如何实例化(甚至编译)CustomerRepo?您需要一个IConfigurationRoot
参数来传递给基本构造函数。喜欢:
public CustomerRepo(IConfigurationRoot configRoot)
: base(configRoot)
{
}
有关基本关键字的信息,请参见https://msdn.microsoft.com/zh-cn/library/hfw7t1ce.aspx。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句