Avoiding circular dependencies in XNA using Ninject 2.0

I am using Ninject as an IOC for an XNA project and want to port it to Ninject 2.0. However, XNA is not injection-friendly, as certain classes must be created in the game class constructor, but must also pass the game class to their constructors. For instance:

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

The article here describes one interaction where the IOC container is explicitly informed about which instance is used to resolve the service.

/// <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);
}

However, I'm not sure how to do this in Ninject 2.0, since I think this is equivalent code

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

still creating a StackOverflowException. Any thoughts, at least about where you can come from here, will be appreciated.

+3
1

, Ninject, , MyGame, NinjectGame Game, Bind() . 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 ();

- , .

+2

Source: https://habr.com/ru/post/1752388/


All Articles