[英]How to call new methods from a class which implements interface
如何调用在接口的具体类中实现的新方法我正在使用结构映射IOC容器。
public interface ICompanyRepository
{
IEnumerable<Company> GetAll();
Company Get(int id);
Company Add(Company item);
bool Update(Company item);
bool Delete(int id);
}
public class CompanyRepository: ICompanyRepository
{
// Provide implementation for all interface methods
//Class CompanyRepository will also have the new method called DisplayLog
public void DisplayLog()
{
//To do
}
}
我正在尝试在我的Customer控制器类中使用结构映射来实现DI,如何告诉我需要调用company2的方法?
_.Scan(x =>
{
x.TheCallingAssembly();
x.AddAllTypesOf<ICompanyRepository>();
// or
});
我的代码:
private readonly ICustomerRepository customerRepository;
public CustomerController(ICustomerRepository CustomerRepository)
{
customerRepository = CustomerRepository;
}
// GET: Customer
public ActionResult Index()
{
var customers = customerRepository.DisplayLog()
//Here i need to call CompanyRepository class methods DisplayLog() how can i call it here ?
// method DisplayLog() is not be shown here
return View(customers);
}
在接口上,您只能调用接口中定义的内容-它是实现该接口的所有类的“公共基础”的定义。 问问自己:如果您获得的ICompanyRepository
类型不实现DisplayLog
怎么办?
这意味着:除了接口方法之外,不可能立即调用其他任何方法。
要在customerRepository
上调用DisplayLog
,有3种方法:
DisplayLog()
添加到接口 毕竟,我不确定您正在做的是DI。 在我对DI的理解中,应该是这样的:
public ActionResult Index(ILogDisplay display)
{
var customers = display.DisplayLog(customerRepository);
return View(customers);
}
ILogDisplay是要注入的单独类的新接口
public interface ILogDisplay
{
public YourResultType DisplayLog(ICustomerRepository);
}
在此示例中,您实际上在类中注入了一个依赖项(ILogDisplay的实现)。
这里有两个问题要提出:
DisplayLog()
在CustomerRepository上下文中是什么意思? 从根本上讲,存储库的行为对于控制器而言应该是未知的,这是控制反转原理的本质。 它关心的只是给定接口为存储库提供的显式协定,方法调用将返回客户。 日志记录是存储库的关注点。
从DI的角度来看,这是一个相当传统的设置,我们可以:
ICompany资料库:
public interface ICompanyRepository() {
IEnumerable<Company> GetAll();
Company Get(int id);
Company Add(Company item);
bool Update(Company item);
bool Delete(int id);
}
客户资料库:
public class CompanyRepository: ICompanyRepository
{
private readonly ILogger logger;
public CompanyRepository(ILogger logger) {
this.logger = logger;
}
// Provide implementation for all interface methods
public Company Get(int id) {
var customers = this.randomCustomerSource.Get(id);
this.logger.Info("Whatever you want to log here");
return customers;
}
}
CustomerController:
public class CustomerController {
private readonly ICustomerRepository customerRepository;
public CustomerController(ICustomerRepository CustomerRepository)
{
customerRepository = CustomerRepository;
}
// GET: Customers
public ActionResult Index()
{
var customers = customerRepository.GetAll()
return View(customers);
}
}
因此,存储库请求一个Ilogger
,控制器请求一个ICompanyRepository
,并将只调用GetAll()
并返回结果。 通常涉及的内容更多,但这是返回数据的控制器的工作流程的最基本要点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.