I'm trying to inject a module by it direct class and by using it interface. For this im using code like this:
interface ITestInterface {
void WriteHash();
}
class TestClass : ITestInterface {
public void WriteHash() => Console.WriteLine(GetHashCode());
}
class FirstModule : NinjectModule {
public override void Load() {
Bind<TestClass>().ToSelf().InSingletonScope();
}
}
class SecondModule : NinjectModule {
public override void Load() {
Bind<ITestInterface>().To<TestClass>().InSingletonScope();
}
}
And when im causing injections like this:
NinjectModule[] modules = { new FirstModule(), new SecondModule() };
IKernel kernel = new StandardKernel(modules);
var foo = kernel.Get<TestClass>();
foo .WriteHash();
var bar = kernel.Get<ITestInterface>();
bar .WriteHash();
Ive got an different hash codes. What am i missing?
1 Answer 1
GetHashCode() returns the same hashcode for objects that are equal. But this you already know hence your question.
Your code is making two separate registrations in the Ninject Kernel and it will not create 1, as you would expect, but two singletons. If would have been nice if Ninject would warn you for this easy to make mistake as for example Simple Injector (my DI container of choice) will do.
Binding multiple interfaces or registration keys to the same implementation must be done like this in Ninject:
Bind<TestClass>().ToSelf().InSingletonScope();
Bind<ITestInterface>().ToMethod(c => c.Kernel.Get<TestClass>());
In Ninject v3 there is a nicer solution:
Bind<TestClass, ITestInterface>().To<TestClass>().InSingletonScope();