我可以使用Ninject将IKernel注入到类中

时间:2017-09-19 20:51:35

标签: c# asp.net-mvc dependency-injection ninject

我想在不使用new的情况下注入AuthenticationService:

IAuthenticationService authenticationService = null;
if (HttpContext.Current != null && HttpContext.Current.Session["LoggedUser"] == null)
{
    HttpContext.Current.Session["LoggedUser"] = new AuthenticationService();
}
authenticationService = (AuthenticationService)HttpContext.Current.Session["LoggedUser"];

我在考虑使用kernel.Get(),但我不知道注入IKernel是否是一个好习惯。我也在考虑使用工厂,但我不知道如何将它与Ninject结合使用。

你会告诉我什么?

1 个答案:

答案 0 :(得分:3)

您不应该将IKernel注入类中,如果您正确利用Ninject提供的IOC容器,则不应该这样做。您可以为服务设置绑定,类似于以下内容:

kernel.Bind<IAuthenticationService>().To<AuthenticationService>();

请注意,根据Ninject设置的方式,这可能会发生在几个不同的地方。如果您提供更多代码,我可以详细说明这一点。对于许多人来说,它位于NinjectWebCommon.cs类中。

然后在你要注入IAuthenticationService的任何课程中,只需传递IAuthenticationService,如下所示:

public class WhateverClass
{
  private IAuthenticationService _authenticationService;

  public WhateverClass(IAuthenticationService authenticationService)
  {
    _authenticationService = authenticationService;
  }

  //some other properties or methods that make use of authentication service here
}