私は現在、プロジェクト用にいくつかの IoC フレームワークをテストしており、Ninject 3 を使用できるようにしたいと考えています。
具体的に型指定されたシングルトンへのバインディングを構成した後、後でサービス タイプを効果的にバインド解除できないように見えるという問題が発生しています。つまり、StandardKernel.TryGet<T>()
を呼び出した後、null 以外の値を返しますStandardKernel.Unbind<T>()
。私の正確な使用法については、以下のスニペットを参照してください。
これは Ninject 3 のバグですか、それとも何か不足していますか?
回避策として、具象型を定数 null 値に再バインドするだけです。しかし、その位置にフォールバックする前に、何かを理解していないかどうかを理解したいと思います。
ちなみに、シングルトン スコープの具象型にバインドされたインターフェイスを指定した場合、バインド解除は期待どおりに機能しますが、シングルトン スコープの自己バインド型の具象型では機能しません。これがバグではない場合 (および追加のカルマ)、動作に違いがある理由を説明できますか?
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!
}