tags:

views:

37

answers:

1

In Castle Windsor there is a feature called forwarded types where you can have one component configuration for multiple services. For example:

var container = new WindsorContainer();
container.Register(
   Component.For<Bar>().Forward<IFoo>()
      .ImplementedBy<FooBar>());
var foo = container.Resolve<IFoo>();
var bar = container.Resolve<Bar>();
Debug.Assert(foo == bar);

(this Debug.Assert works 'cause Windsor by default registers things as singletons)

How to achieve this in Ninject (version 2) ?

A: 

I'm interested to see if anyone else chimes in with a better solution, but here's an option:

Use a special IProvider when binding to do the forward:

public class ForwardProvider<ForwardType> : Ninject.Activation.IProvider
{
    #region IProvider Members
    public object Create( IContext context )
    {
        return context.Kernel.Get<ForwardType>();
    }

    public Type Type
    {
        get { return typeof( ForwardType ); }
    }
    #endregion
}

and then when binding:

IKernel kernel = new StandardKernel();
kernel.Bind<ITestAdapter>().To<TestAdapter>().InSingletonScope();
kernel.Bind<IAnotherAdapter>().ToProvider<ForwardProvider<ITestAdapter>>();

and my test:

var foo = kernel.Get<ITestAdapter>();
foo.Indicator = 5;

var bar = kernel.Get<TestAdapter>();
Assert.That( foo.Indicator, Is.EqualTo( 5 ) );

var baz = kernel.Get<IAnotherAdapter>();
Assert.That( baz.Indicator, Is.EqualTo( 5 ) );
dave thieben
Accepting the answer, but was hoping that it is available OOB.
Artur