c#ninject实例化类中的注入依赖

时间:2019-07-06 00:52:36

标签: c# dependency-injection ninject

我有一个C# MVC项目,使用Repository PatternNinject(DI)。一切正常。

在存储库内部,我实例化一个类来处理对外部API的某些调用,如下所示:

public class EmployeeRepository : IEmployeeRepository
    {
        private readonly AppState _appState;

        public EmployeeRepository(IAppStateProvider appStateProvider)
        {
            _appState = appStateProvider.AppState;
        }

        public bool ProcessEmployee(long employeeId, object data)
        {
            var api = new ExternalAPI(_appState);
            api.PostData(data);
            return true;
        }
}

然后我的ExternalAPI.cs类是:

public class ExternalAPI: BaseRepository
    {
        [Inject]
        public ILogRepository Logger { get; set; }

        private readonly AppState _appState;

        public ExternalAPI(AppState appState)
        {
            _appState = appState;
        }


        private bool PostData(object data)
        {
            bool returnVal = true;

            // Some code here....

            Logger.InsertLog(data); // HERE Logger IS NULL

            return returnVal;
        }
 }

在这里我得到一个例外,因为Loggernull

在我的主项目NinjectWebCommon.cs文件中,我正确注册了依赖项:

private static void RegisterServices(IKernel kernel)
        {

            kernel.Bind(typeof(ILogRepository)).To(typeof(Data.LogRepository));
         }
  

任何线索为何[Inject]中的ILogRepositoryExternalAPI类中不起作用?

可能是因为从EmployeeRepository我创建了该类的新实例:

var api = new ExternalAPI(_appState);
  

任何建议以及如何使ILogRepository类的ExternalAPI注入工作正常?

1 个答案:

答案 0 :(得分:0)

引用Explicit Dependencies Principle

  

方法和类应明确要求(通常通过方法参数或构造函数参数)它们所需的任何协作对象,以使其正常运行。

ExternalAPI依赖于ILogRepositoryAppState,因此应该注入其中

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依赖于ExternalAPI,因此应该注入其中。

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));
    //...
 }