CodeRedick
CodeRedick

Reputation: 7415

Do I have to call kernel.Get to instantiate an object when using Ninject?

So many of the examples for Ninject are very, very basic. It's either just a controller, or they create the kernel and the object's in a single function for demonstration purposes.

So for some reason I thought that you could just instantiate an object like normal, and Ninject would intercept that and work. For instance:

public class foo 
{
    public foo(IInjectable injected)
    {
       //stuff
    }
}

Then somewhere in another class you could do:

var fooObject = new foo();

So am I supposed to use kernel.get instead?

Then, if I DO need to keep calling the kernel how do I pass that around to everything that needs it?

Upvotes: 1

Views: 388

Answers (2)

Daniel Marbach
Daniel Marbach

Reputation: 2314

If you design your application well then there should only be only a single Kernel.Get request happening in your application (often via something like like Ninject.MVC3). Usually that is where the root object of your application gets instantiated (for example MainViewModel of your application shell). All other types simply declare their dependencies in the constructor without knowing who is responsible for creating and managing their dependencies. Little example

public class Main {
   // Somewhere
   var mainViewModel = Kernel.Get<MainViewModel>();
   mainViewModel.Initialize();
}

public class MainViewModel {
    ctor(ISectionViewModelFactory factory, ISectionViewModel sectionViewModel) {
    }

    public void Initialize() {
       // use injected factory etc.
    }
}

public class ApplicationModule : NinjectModule {

   public override void Load() {
      Bind<ISectionViewModel>().To<SectionViewModel>();
      Bind<ISectionViewModelFactory>().ToFactory(); // <-- requires factory extension
   }
}

and the application builds itself up without accessing the kernel elsewhere.

See the factory extension for the ToFactory() bit.

Upvotes: 1

McGarnagle
McGarnagle

Reputation: 102763

Your approach here would only work if you also inject foo (in general it's not a good idea to start injecting the kernel into your classes, as it starts to un-invert the inversion of control, so to speak).

It's hard to tell without some context, but let's say your code above is contained in another class bar. Then you'd proceed like so:

public class bar
{
    foo _fooObject;

    public bar(foo fooObject)
    {
        _fooObject = fooObject;
    }
}

And then of course the binding for foo would be set up, for example:

Bind<foo>.ToSelf();

If you need to create multiple instances of foo within bar, then you could use a factory:

public class bar
{
    fooFactory _factory;

    public bar(fooFactory factory)
    {
        _factory = factory;
    }

    void baz()
    {
        foo fooObject = _factory.GetNew();
    }
}

Upvotes: 0

Related Questions