我們在我們的項目中使用了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