使用构造函数注入Ninject手动初始化

时间:2012-04-05 03:47:25

标签: ninject

当我手动初始化类时,如何进行构造函数注入?

public class ApiKeyHandler : DelegatingHandler
{
    private IApiService apiService;

    public ApiKeyHandler(IApiService apiService)
    {
        this.apiService = apiService;
    }
}

初​​始化:

var apiKey = new ApiKeyHandler(/*inject here */);

我如何做到这一点?我的绑定和所有内容都已设置完毕。

1 个答案:

答案 0 :(得分:0)

你想做这样的事情:

var apiKey = new ApiKeyHandler(kernel.Get<IApiService>());

但是,为什么不注入ApiKeyHandler本身?

var apiKey = kernel.Get<ApiKeyHandler>();

Here is an article about Ninject

您基本上希望在代码的开头设置它并使其全局可用:

public IKernel kernel  = new StandardKernel();

...

kernel.Bind<IApiService>()
      .To<SomeConcreteApiService>();