我们在我们的项目中使用了Ruben的方法,但发现它并不直观,为什么你要回到绑定中的内核。我创建了一个扩展方法和辅助类(如下图),所以你可以这样做:
kernel.Bind<IService>().ToExisting().Singleton<Service>();
这似乎更清楚地表达意图给我。
public static class DIExtensions
{
public static ToExistingSingletonSyntax<T> ToExisting<T>(this IBindingToSyntax<T> binding)
{
return new ToExistingSingletonSyntax<T>(binding);
}
}
// Had to create this intermediate class because we have two type parameters -- the interface and the implementation,
// but we want the compiler to infer the interface type and we supply the implementation type. C# can't do that.
public class ToExistingSingletonSyntax<T>
{
internal ToExistingSingletonSyntax(IBindingToSyntax<T> binding)
{
_binding = binding;
}
public IBindingNamedWithOrOnSyntax<T> Singleton<TImplementation>() where TImplementation : T
{
return _binding.ToMethod(ctx => ctx.Kernel.Get<TImplementation>()).InSingletonScope();
}
private IBindingToSyntax<T> _binding;
}
顺便说一句我相信在Ninject的2.3和2.4版本中有一些不一致性正在清理,确保以这种方式重复使用的内容只会被激活和/或清理一次 – 2011-02-18 16:12:50
请参阅V3特定的答案:http:///堆栈溢出。com/questions/10206049/ninject-is-it-it-possible-to-bind-different-interfaces-to-the-same-instance-of -ac- – 2012-09-12 08:53:00
related:http://stackoverflow.com/questions/8303661/ninject-绑定接口到接口/ 8303826#comment16639462_8303826 – 2012-09-12 10:12:56