Book Image

Mastering Ninject for Dependency Injection

By : Daniel Baharestani
Book Image

Mastering Ninject for Dependency Injection

By: Daniel Baharestani

Overview of this book

Dependency injection is an approach to creating loosely coupled applications. Maintainability, testability, and extensibility are just a few advantages of loose coupling. Ninject is a software library which automates almost everything that we need in order to implement a dependency injection pattern. Mastering Ninject for Dependency Injection will teach you everything you need to know in order to implement dependency injection using Ninject in a real-life project. Not only does it teach you about Ninject core framework features that are essential for implementing dependency injection, but it also explores the power of Ninject's most useful extensions and demonstrates how to apply them. Mastering Ninject for Dependency Injection starts by introducing you to dependency injection and what it's meant for with the help of sufficient examples. Eventually, you'll learn how to integrate Ninject into your practical project and how to use its basic features. Also, you will go through scenarios wherein advanced features of Ninject, such as Multi-binding, Contextual binding, providers, factories and so on, come into play. As you progress, Mastering Ninject for Dependency Injection will show you how to create a multilayer application that demonstrates the use of Ninject on different application types such as MVC, WPF, WCF, and so on. Finally, you will learn the benefits of using the powerful extensions of Ninject.
Table of Contents (12 chapters)

Custom providers


Providers are specialized factory classes that Ninject uses in order to instantiate resolved types. Whenever we bind a service type to a component, we are implicitly associating that service type to a provider that can generate instances of that component. This hidden provider is a generic factory, which can create instances of every given type, and is called StandardProvider. Although we can often rely on StandardProvider without having to bother about what it does behind the scenes, Ninject also allows us to create and register our custom providers just in case we need to customize the activation process as follows:

Bind<IService>().ToProvider<MyService>();
public class MyServiceProvider : Provider<MyService>
{
    protected override MyService CreateInstance(IContext context)
    {
        return new MyService();
    }
}

Although extending the Provider<T> class is the recommended way to create a custom provider, implementing the IProvider interface...