2010-06-30 5 views
3

나는 Ninject를 XNA 프로젝트의 IOC로 사용하여 Ninject 2.0으로 마이그레이션하려고했습니다. 그러나 XNA는 특정 클래스가 게임 클래스의 생성자에서 인스턴스화되어야하고 게임 클래스를 생성자에게 전달해야하기 때문에 종속성 삽입에 우호적이지 않습니다. 예를 들어 :Ninject 2.0을 사용하여 XNA의 순환 의존성 피하기

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

기사 here은 IOC 컨테이너가 명시 적으로 서비스를 해결하기 위해 사용하는 것을 예를 통보되는 경우, 하나의 해결 방법에 대해 설명합니다. 제가 생각하는 것은 여전히 ​​해당 코드

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을 생산으로

/// <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에서이 작업을 수행하는 방법에 대한 불확실 해요. 적어도 여기에서 진행하는 것에 대한 생각은 인정 될 것입니다.

+0

다운로드 소스 트렁크를 다운로드하십시오. 그건 2 분 걸릴거야. 그런 다음 테스트를 살펴보면 구문에 대한 간단한 명확한 예를 제공합니다. 그러면이 글을 게시하는 데 걸린 시간보다 짧은 시간 내에 답변 할 수 있습니다 (진지하게) –

답변

2

문제가 Ninject에 자동으로 Bind() 다시 호출되는 경우 MyGame, NinjectGameGame 사이에 이전에 설정 한 바인딩을 교체하지에서 오는 것으로 생각된다. 이 솔루션은 다시 다음 중 하나 Unbind(), Bind() 전화, 또는 그냥 바인딩이 존재하지 않은 경우는 다른 문제를 예외를 던지거나 발생하지 않습니다 때문에

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

을하기로 결정했습니다 것입니다 Rebind()를 호출하는 것입니다 전화하기 전에.

관련 문제