没有给出与所需形式参数“ mapper”相对应的参数

时间:2018-11-30 05:47:05

标签: c# oop repository-pattern

我确定这是一个基本的OOP问题,但是我试图将ContactsRepository用作基类,并在OrganizationRepository类中使用其方法,但出现错误: 没有给出与所需形式参数'mapper'对应的参数

// OrganizationRepository类

public class OrganizationRepository : ContactsRepository, IOrganizationRepository
    {

        #region fields   
        private readonly GreyWorldDB_DevEntities _context;
        private readonly IMapper _mapper;
        private readonly UserManagement _userManagement;
        #endregion


        #region Ctor
        public OrganizationRepository(IMapper mapper, GreyWorldDB_DevEntities context, UserManagement userManagement)
        {
            _mapper = mapper;
            _context = context;
            _userManagement = userManagement;
        }
        #endregion

        #region  Actions

            //Action methods
        #endregion

        #region Private Methods

            //private methods
        #endregion
    }

// ContactsRepository类

public class ContactsRepository : IContactsRepository
    {

        #region fields   
        private readonly GreyWorldDB_DevEntities _context;
        private readonly IMapper _mapper;
        private readonly UserManagement _userManagement;
        #endregion

        #region Ctor
        public ContactsRepository(IMapper mapper, GreyWorldDB_DevEntities context, UserManagement userManagement)
        {
            _mapper = mapper;
            _context = context;
            _userManagement = userManagement;
        }
        #endregion

        #region  Actions

            //Action methods
        #endregion

        #region Private Methods


        #endregion

    }

没有给出与“ ContactsRepository.ContactsRepository(IMapper,GreyWorldDB_DevEntities,UserManagement)”的所需形式参数“ mapper”相对应的参数

1 个答案:

答案 0 :(得分:1)

创建派生类的实例时,将在运行派生类的构造函数之前调用基类的构造函数。类之间的构造函数不必相同,但是如果基类的构造函数不是无参数的,则仍然需要将其所需的参数传递给它:

public class BaseClass
{
    public BaseClass(string name)
    {
    }
}

public class DerivedClass: BaseClass
{
    public DerivedClass() : base("test")
    {
    }
}

此外,我不确定为什么要在基类和派生类中重新定义相同的私有字段。相反,您应该使它们protected在基类中,让基部构造函数填充它们,然后只需从派生类传递它们即可。您的代码最终应该看起来像这样:

public class ContactsRepository : IContactsRepository
{
    protected readonly GreyWorldDB_DevEntities _context;
    protected readonly IMapper _mapper;
    protected readonly UserManagement _userManagement;

    public ContactsRepository(IMapper mapper, GreyWorldDB_DevEntities context, UserManagement userManagement)
    {
        _mapper = mapper;
        _context = context;
        _userManagement = userManagement;
    }
}

public class OrganizationRepository : ContactsRepository, IOrganizationRepository
{
    public OrganizationRepository(IMapper mapper, GreyWorldDB_DevEntities context, UserManagement userManagement)
        : base(mapper, context, userManagement)
    {
    }
}