以下是我的应用程序如何调用数据库: Web应用程序->业务层->数据层
一切都使用依赖注入(inject)。
例如:
在我的 Web 应用程序的 Controller 中,我进行如下调用:
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 应用程序注入(inject)一个 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();
...
}
}
最佳答案
无论依赖注入(inject)如何,您将如何实例化(甚至编译)CustomerRepo?您需要一个 IConfigurationRoot
参数来传递到基本构造函数。喜欢:
public CustomerRepo(IConfigurationRoot configRoot)
: base(configRoot)
{
}
参见https://msdn.microsoft.com/en-us/library/hfw7t1ce.aspx有关基本关键字的信息。
关于c# - 同时使用继承和依赖注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35325687/