Reputation: 274
I have a little problem I can't wrap my head around in relation to Dependency Injections. I learned how to inject dependency for .net mvc 5 controllers using Ninject. However, I can't figure out how to inject dependencies for my own classes.
For example I have a Resource class.
public class Resource
{
public IResourceLoader ResourceLoader {get;set}
public Resource(IResourceLoader ResourceLoader)
{
this.ResourceLoader = ResourceLoader;
}
}
Where IResourceLoader can be implemented to load different types of resources such as XMLLoader. So is it possible to use Ninject to automatically send an instance of XMLLoader when I do
Resource xmlResource = new Resource(/*do something here/*);
Or better yet if I have a Banner class that inherits from Resource that sets a string resourceType to "xml" and have Ninject filter instances based on that string.
Do I have to implement a factory pattern and do it myself.
Thanks
Upvotes: 0
Views: 157
Reputation: 3835
If you're using Ninject, and in a web project, you should have a NinjectWebCommon.cs
class in the App_Start
folder?
In the RegisterServices
method you could add:
kernel
.Bind<IResourceLoader>()
.ToMethod<IResourceLoader>(InstantiateResourceLoader)
And then in the same class, implement the method like so:
private static IResourceLoader InstantiateResourceLoader(IContext ctx) {
// Put in whatever logic you need to decide on which loader you want to return
// Use ctx.Kernel.Get<WhatEver>() if you need something from the DI
return new XMLLoader();
}
Upvotes: 1
Reputation: 25251
The simple use of DI is where you first register your dependencies (Ninject calls this 'type bindings'):
Bind<IResourceLoader>().To<XMLLoader>();
You can then get an instance of Resource by doing:
IKernel kernel = new StandardKernel();
var resource = kernel.Get<Resource>();
and Ninject will wire-up the constructor types it knows about.
Alternatively, there are several other ways to create dependencies, including, for example the ability to completely control parameters used to create the resource instance:
Bind<IResourceLoader>().ToMethod(context => new XMLResourceLoader("schema.xsd"));
Ninject also supports something it calls Contextual Binding, where basically you can do something like this:
Bind<IResourceLoader>().To<SimpleResourceLoader>();
Bind<IResourceLoader>().To<XMLResourceLoader>().Named("XML");
public class Banner : Resource
{
public Banner([Named("XML")] IResourceLoader resourceLoader)
: base(resourceLoader) { }
}
Upvotes: 1