Newbie Ninject question klaxxon.
I have the following classes and interfaces which describe a dependency I need to inject, and a depender into which a concrete instance of the dependency needs to be injected.
public interface IDependency { }
public class FooDependency : IDependency { }
public class Depender
{
[Inject]
public IDependency Dependency { get; set; }
public bool DependencyIsNull()
{
return Dependency == null;
}
}
I have setup my bindings with a NinjectModule instance, like so.
public class Bindings : NinjectModule
{
public override void Load()
{
Bind<IDependency>().To<FooDependency>();
}
}
And here's a unit test method which asserts that the dependency has been injected into the depender.
[TestMethod]
public void TestMethod1()
{
var kernel = new StandardKernel(new Bindings());
var bar = new Depender();
Assert.IsFalse(bar.DependencyIsNull());
}
I'm clearly doing something fundamentally wrong, as I would have expected the test to pass, but it doesn't.
Your object isn't created by your kernel. Everything needs to be created by the kernel to have dependencies injected:
// option a (recommended)
var kernel = new StandardKernel(new Bindings());
var bar = kernel.Get<IDependency>();
Assert.IsFalse(bar.DependencyIsNull());
// option b (not recommended.. but do-able)
var kernel = new StandardKernel(new Bindings());
var bar = new Depender();
kernel.Inject(bar); // injects after the fact
Assert.IsFalse(bar.DependencyIsNull());
Also, you should have that DependencyIsNull method in your interface:
public interface IDependency {
bool DependencyIsNull();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With