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

c# ninject inject dependency in a instantiated class

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

在存储库中,我正在实例化一个 class 来处理对外部 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.csclass是:

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

Any clue why the [Inject] of ILogRepository is not working in the ExternalAPI class?

可能是因为我从 EmployeeRepository 创建了一个新实例 class:

var api = new ExternalAPI(_appState);

Any advice and how can I make the injection of ILogRepository work in ExternalAPI class?

引用Explicit Dependencies Principle

Methods and classes should explicitly require (typically through method parameters or constructor parameters) any collaborating objects they need in order to function correctly.

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