【问题标题】:Ninject Kernel.Get<T> Instance CreationNinject Kernel.Get<T> 实例创建
【发布时间】:2023-04-08 18:42:01
【问题描述】:

今天我在我的代码库中发现了一个错误,其中一个注入的依赖项据说在它被注入的类中存在。当我期望总是注入一个新的依赖实例时,我得到了一个旧实例。我设法通过从下面的简化 sn-p 中删除行 this.Kernel.Get&lt;IA&gt;() 来清理错误。虽然这不是项目的全貌,但它是用于犯罪者的确切配置。

internal sealed class MyNinjectModule : NinjectModule
{
    public override void Load()
    {
        this.Bind<IA>().To<A>();

        this.Bind<B>().ToSelf()
            .WithConstructorArgument(this.Kernel.Get<IDependencyOne>())
            .WithConstructorArgument(this.Kernel.Get<IDependencyTwo>())
            .WithConstructorArgument(this.Kernel.Get<IA>())
            .WithConstructorArgument<uint>(50U);
    }

因此,虽然我总是会得到B 的新实例,但我会得到IA 的旧实例。谁能帮我了解IResolutionRoot 中的.Get&lt;T&gt; 扩展方法的生命周期?我一直认为对.Get&lt;T&gt; 的调用会根据我的绑定设置的先前配置生成一个实例。这是 Ninject 的正确行为吗?

信息

  • 使用 Ninject 3.2.2.0
  • C# 5、.Net 4.5 框架
  • WPF 应用程序

【问题讨论】:

    标签: c# wpf dependency-injection ninject inversion-of-control


    【解决方案1】:

    您可以尝试将 lambda 表达式传递给 .WithConstructorArgument()

    this.Bind<B>().ToSelf()
            .WithConstructorArgument(() => this.Kernel.Get<IDependencyOne>())
            .WithConstructorArgument(() => this.Kernel.Get<IDependencyTwo>())
            .WithConstructorArgument(() => this.Kernel.Get<IA>())
            .WithConstructorArgument<uint>(50U);
    

    我认为您的代码在开始时获取 IA,然后在检索时始终将其传递给 B 的构造函数。另一方面,每次构造 B 时都应该调用 Lambda 方法。

    或者,您可以尝试仅在模块中指定命名的 uint 变量:

    this.Bind<B>().ToSelf()
            .WithConstructorArgument<uint>("uintParamName", 50U);
    

    只要有绑定,Ninject 就应该解析剩余的参数。

    【讨论】:

    • 我不能在明天之前尝试这个,但是当然可以!我完全忽略了我的代码中缺少 lambda。那将是完全有道理的。谢谢。
    • 非常好的答案,尤其是关于大多数参数规范的部分是多余的!对于容器注入的东西,不需要使用.WithConstructorArgument()。开箱即用!
    猜你喜欢
    • 1970-01-01
    • 2017-01-30
    • 2012-06-16
    • 1970-01-01
    • 2016-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-25
    相关资源
    最近更新 更多