gpt4 book ai didi

c# - 我可以使用 Ninject 将 IKernel 注入(inject)类吗

转载 作者:太空宇宙 更新时间:2023-11-03 22:54:02 25 4
gpt4 key购买 nike

我想在不使用 new 的情况下注入(inject) 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(),但我不知道注入(inject) IKernel 是否是一个好习惯。我也在考虑使用工厂,但我不知道如何将它与 Ninject 结合起来。

你有什么建议?

最佳答案

您不应将 IKernel 注入(inject)到类中,如果您正确利用了 Ninject 提供的 IOC 容器,则没有必要这样做。您可以为服务设置类似于以下内容的绑定(bind):

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

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

然后在任何你想注入(inject)的类中IAuthenticationService into,只需传入 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
}

关于c# - 我可以使用 Ninject 将 IKernel 注入(inject)类吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46309572/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com