Did I mention how much I like Ninject :) I have been spending a bit more time, but not as much as I would like, sifting through the Ninject unit tests and I came across the InlineModule, factory methods, and the concept of providers. I thought I would mention these ideas in a post, if like me, you are learning Ninject and looking for help anywhere you can find it :)
You can read my other samples and tutorials on Ninject Dependency Injection:
Ninject Inline Module
As I mentioned in a previous Ninject tutorial, you typically register your services with Ninject in modules and then pass those modules into the constructor of a Kernel, like StandardKernel. I don't suggest deviating from that standard practice, but I really like the InlineModule which allows you to register your services inline, hence the name :)
private static void Main(string[] args)
{
IKernel kernel = new StandardKernel(new InlineModule(
m => m.Bind<IValidator>().To<Validator>(),
m => m.Bind<ILogger>().To<Logger>(),
m => m.Bind<ICache>().To<Cache>()
));
IValidator validator = kernel.Get<IValidator>();
ILogger logger = kernel.Get<Logger>();
ICache cache = kernel.Get<ICache>();
}
Notice how I am registering my bindings inline to the module constructor as opposed to creating a separate module class and overriding the Load method to register those services. You'll see the InlineModule being used quite a bit in the unit tests and I just wanted to mention it here because I don't believe it is in the Ninject Documentation online.
Ninject Factory Methods
You can also bind to a FactoryMethod when specifying a binding. Let's replace the binding of the Logger Class mentioned above with a simple Lambda Expression that creates a new instance of the logger class using its default constructor. Here is just a snippet of the above code showing the Factory Method:
IKernel kernel = new StandardKernel(new InlineModule(
m => m.Bind<ILogger>().ToFactoryMethod(() => new Logger())
));
You don't need to use a Lambda Expression as above, but I did want to show how easy it is to use a Factory Method when binding with Ninject.
Ninject Providers
You can also bind to a provider. In fact, that is how Ninject works under the covers. Let's create a simple CacheProvider and bind that to ICache.
IKernel kernel = new StandardKernel(new InlineModule(
m => m.Bind<ICache>().ToProvider<CacheProvider>()
));
public class CacheProvider : SimpleProvider<ICache>
{
protected override ICache
CreateInstance(IContext context)
{
return new Cache();
}
}
This is nothing but a simple factory under the covers, but you can do so much more with it if you wish.
Conclusion
If you are thinking about using Ninject for dependency injection / inversion of control, I hope this helps you get started in your adventure.
David Hayden