c# - 同时使用继承和依赖注入(inject)

标签 c# asp.net asp.net-mvc inheritance dependency-injection

以下是我的应用程序如何调用数据库: 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/

相关文章:

c# - Entity Framework与MVC的关系

c# - 如何在 Kentico CMS 中创建 "back"链接?

C# 查找相关文档片段用于搜索结果显示

c# - 输入缓冲区中的串行输出?

c# - 如何在ado net中使用UPDATE

c# - Linq 中的WhereSelectArrayIterator 是什么?

c# - 在 asp.net 中强制整个站点使用 https 的最佳方法?

c# - MVC 4 - 从 View 传递数据 => Controller

javascript - 在 javascript 中用于日期验证的正则表达式

c# - 为什么我的 View 不使用 EditorTemplates 文件夹来执行创建操作?