1

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?

asked Jun 12, 2016 at 19:17

1 Answer 1

2

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();
answered Jun 12, 2016 at 21:23
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much, and one more question about this: Can I use separete modules to make injection of one class with different interfaces like i do this before? I want to separate injeciton logic to few modules, but your answer help me to resolve the biggest part of my problem. Thank you again.
I'm not sure. With the v3 syntax You obviously can't.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.