2010-06-30 86 views
3

我一直在使用Ninject作爲XNA項目的IOC,並且希望將它遷移到Ninject 2.0。然而,XNA並不依賴注入友好,因爲某些類必須在遊戲類的構造函數中實例化,但也必須將遊戲類傳遞給它們的構造函數。例如:使用Ninject 2.0避免XNA中的循環依賴關係

public MyGame() 
{ 
    this.graphicsDeviceManager = new GraphicsDeviceManager (this); 
} 

的一篇文章here介紹一個變通,在IOC容器明確告知的用什麼實例來解析服務。

/// <summary>Initializes a new Ninject game instance</summary> 
/// <param name="kernel">Kernel the game has been created by</param> 
public NinjectGame (IKernel kernel) 
{ 
    Type type = this.GetType(); 

    if (type != typeof (Game)) 
    { 
     this.bindToThis (kernel, type); 
    } 
    this.bindToThis (kernel, typeof (Game)); 
    this.bindToThis (kernel, typeof (NinjectGame)); 
} 

/// <summary>Binds the provided type to this instance</summary> 
/// <param name="kernel">Kernel the binding will be registered to</param> 
/// <param name="serviceType">Service to which this instance will be bound</param> 
private void bindToThis (IKernel kernel, Type serviceType) 
{ 
    StandardBinding binding = new StandardBinding (kernel, serviceType); 
    IBindingTargetSyntax binder = new StandardBinder (binding); 

    binder.ToConstant (this); 
    kernel.AddBinding (binding); 
} 

不過,我不確定如何在Ninject 2.0做到這一點,因爲我會覺得是等效代碼

if (type != typeof (Game)) 
{ 
    kernel.Bind (type).ToConstant (this).InSingletonScope(); 
} 
kernel.Bind (typeof (Game)).ToConstant (this).InSingletonScope(); 
kernel.Bind (typeof (NinjectGame)).ToConstant (this).InSingletonScope(); 

仍然生產StackOverflowException。任何想法,至少在哪裏從這裏開始將不勝感激。

+0

去下載源的主幹。這將需要2分鐘。然後查看測試 - 它們提供了簡短的語法示例。然後,您可以在更短的時間內回答這個問題,而不是讓您發佈此問題(認真) – 2010-06-30 09:58:47

回答

2

這樣看來,這個問題是來自Ninject不會自動更換那名如果Bind()又被稱爲MyGameNinjectGameGame之間先前設置的綁定。解決的辦法是再打電話要麼Unbind(),然後Bind(),或者只是打電話Rebind(),這是我選擇了做

if (type != typeof (Game)) 
{ 
    kernel.Rebind (type).ToConstant (this).InSingletonScope(); 
} 
kernel.Rebind (typeof (Game)).ToConstant (this).InSingletonScope(); 
kernel.Rebind (typeof (NinjectGame)).ToConstant (this).InSingletonScope(); 

因爲如果綁定不存在,它不會拋出異常或導致任何其他問題在電話會議之前。