参考
Explicit Dependencies Principle
方法和类应该显式地(通常通过方法参数或构造函数参数)需要它们所需的任何协作对象才能正常工作。
ExternalAPI
依赖于
ILogRepository
和
AppState
所以这就是应该注入的
public class ExternalAPI: BaseRepository, IExternalAPI {
private readonly ILogRepository logger;
private readonly AppState _appState;
public ExternalAPI(IAppStateProvider appStateProvidere, ILogRepository logger) {
_appState = appStateProvidere.AppState;
this.logger = logger;
}
public bool PostData(object data) {
bool returnVal = true;
// Some code here....
logger.InsertLog(data); // HERE Logger IS NULL
return returnVal;
}
}
EmployeeRepository
依赖于
外部API
所以这就是应该注入的。
public class EmployeeRepository : IEmployeeRepository {
private readonly IExternalAPI api;
public EmployeeRepository(IExternalAPI api) {
this.api = api;
}
public bool ProcessEmployee(long employeeId, object data) {
api.PostData(data);
return true;
}
}
确保向容器注册了所有必需的依赖项
private static void RegisterServices(IKernel kernel) {
//...
kernel.Bind(typeof(ILogRepository)).To(typeof(Data.LogRepository));
kernel.Bind(typeof(IExternalAPI)).To(typeof(ExternalAPI));
//...
}