Reputation: 5626
Let's say I have the following interface and class:
public interface IMyService
{
void DoSomething();
}
public class MagicInterfaceImplementor<T>
{
public T GetImplementation()
{
// Not relevant.
}
}
The only way to get an instance of IMyService
is through MagicInterfaceImplementor<IMyService>
. I can obviously setup injection pretty easily for MagicInterfaceImplementor<IMyService>
:
Bind<MagicInterfaceImplementor<IMyService>().ToSelf();
[Strictly, this isn't necessary in this particular instance, but I'm doing a bit more with the binding in the actual case.]
My question is - how do I bind IMyService
?
I think I can do this, but I'm not sure that it's the best way, since I'm explicitly calling the Kernel, which is typically frowned upon:
Bind<IMyService>().ToMethod(context => {
return ((MagicInterfaceImplementor<IMyService>)
context.Kernel.GetService(typeof(MagicInterfaceImplementor<IMyService>)))
.GetImplementation();
});
Any suggestions of a more proper way to do this would be appreciated.
Upvotes: 0
Views: 67
Reputation: 3289
Maybe it would be interesting what exactly MagicImplementor does. So this is more of a guess, but maybe a Provider might help you.
https://github.com/ninject/ninject/wiki/Providers,-Factory-Methods-and-the-Activation-Context
Otherwise you can simply write
Bind<IMyService>().ToMethod(ctx => ctx.Kernel.Get<MagicInterfaceImplementor<IMyService>>().GetImplementation());
Upvotes: 1