c# - 如何在 Ninject 3 中解除具体的自绑定(bind)单例绑定(bind)?

标签 c# ninject

我目前正在为一个项目测试一些 IoC 框架,我希望能够使用 Ninject 3。

我遇到了一个问题,在配置与具体类型的单例的绑定(bind)后,我似乎无法在以后有效地解除服务类型的绑定(bind)。即StandardKernel.TryGet<T>()调用 StandardKernel.Unbind<T>() 后返回非空值。请参阅下面的代码片段了解我的确切用法。

这是 Ninject 3 中的错误,还是我遗漏了什么?

作为解决方法,我可以简单地将具体类型重新绑定(bind)到常量 null 值。但我更愿意在回退到那个位置之前了解我是否没有摸索到某些东西。

顺便说一句,如果我指定绑定(bind)到单例范围中的具体类型的接口(interface),但不指定单例范围中的自绑定(bind)具体类型,则解除绑定(bind)会按预期工作。如果这不是一个错误(以及额外的业力),你能解释一下为什么行为存在差异吗?

public class MyServiceType : IDisposable
{
    public bool IsDisposed { get; private set; }
    public void Dispose()
    {
        IsDisposed = true;
    }
}

static void Main(string[] args)
{
    var kernel = new StandardKernel();

    kernel.Bind<MyServiceType>().ToSelf().InSingletonScope();

    var instance = kernel.TryGet<MyServiceType>();
    Debug.Assert(instance != null && !instance.IsDisposed);

    // release the instance
    kernel.Release(instance);
    Debug.Assert(instance.IsDisposed);
    instance = null;

    // unbind the service
    kernel.Unbind<MyServiceType>();

    // uncomment below for workaround
    // kernel.Rebind<MyServiceType>().ToConstant((MyServiceType)null); 

    // after unbinding should no longer be able to get an instance of the service
    instance = kernel.TryGet<MyServiceType>();
    Debug.Assert(instance == null);  // <---- this is failing!
}

最佳答案

这是因为即使没有绑定(bind),Ninject 也会尝试构造您的对象。如果它有一个无参数构造函数,它将使用它,否则它将尝试使用容器中找到的依赖项来构造它。

为了向自己证明这一点,即使您跳过 MyServiceType 的初始绑定(bind),并且仍然执行 TryGet,您也会获得一个实例。

或者,您可以尝试在绑定(bind)和释放实例后解析该实例,并断言它们实际上是同一类的不同实例。

关于c# - 如何在 Ninject 3 中解除具体的自绑定(bind)单例绑定(bind)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12398145/

相关文章:

asp.net-mvc - DbContext 错误?检索新保存的记录后导航属性为空

c# - 使用 NInject 在 WPF 中注入(inject)没有无参数构造函数的 View 模型类

c# - .NET 平台标准中有哪些平台?

c# - 通过 TCP C# 接收结构

c# - 443 端口的备用端口是什么?

c# - 使用基于 Ninject 约定的绑定(bind)的正确方法是什么?

c# - NinjectModule 的加载顺序

c# - 当辅助字段为特定值时,使用NEST增强Elasticsearch结果

c# - 具有内联架构的 XDocument。 SchemaInfo 为空

c# - 洋葱架构日志记录 NHibernate