User:Jasonmail04/sandbox

From Wikipedia, the free encyclopedia
Ninject
Stable release
v3.2.2 / early 2012
Written inLINQ
Platform.NET languages (C#, F#, VB.NET)
Size1.3 MB
Websitewww.ninject.org

Ninject is one of the newest framework for .NET application. It helps to split application into a collection of sloppy-coupled, highly-connected pieces, and combine them together in a flexible manner by using dependency injection technique. It makes user's job easy to write, reuse, test, and modify their code to support latest software's architecture. Ninject makes use of the lightweight code generation in the CLR(Common Language Runtime), and supports most major facilities offered by the competing frameworks.[1] It is one of the many available open-source dependency injection containers.

Introduction[edit]

Every software development project involves breaking the whole component into many individual components, and later combining them together in-order for the software to work. Ninject[2] aims to solve this. First, many other frameworks use XML configuration files to guide the framework. Since we often need to write out the assembly-qualified type name for each types, this causes the configuration to be more complex and verbose. However, Ninject provides a fluent interface to declare type bindings.

Furthermore, Ninject aims to keep things simple. Most of other frameworks are complicated and heavyweight, and it needs user to add several assembly dependencies to project.

Third, With Ninject we have a strong, flexible form of binding known as "contextual binding". Ninject can be aware of its environment, and alter the implementation for a given service during activation.

Features[edit]

  • It is designed in a way to use features, that are often necessary, with ease. You need not know all the advanced features for using the basic.
  • Developed with only .NET base library. It doesn't use any third party libraries. Thus making the application which uses ninject, to deal with very minimal dependencies.
  • CLR has a light-weight code generation feature which is used by Ninject to make the performance better.
  • Doesn't use any XML configuration files like other dependency injectors.
  • It is based on Component-based-architecture[3]. Which means the software can be customized according to the application and usage.
  • It can also inject different implementations of a service during run-time. i.e; depending on the context.

History[edit]

There were many IOC Containers prior to Ninject. Ninject version-1 wasn't the first Dependency Injection container. Ninject version-2 wasn't backward compatible with version-1. Version-3 doesn't use XML configuration files to guide the framework to pull up every component of the application. It uses "embedded domain-specific language" to declare the bindings.

Getting Started[edit]

Below are few examples that illustrate usage of this library.

Hello Ninject![edit]

Once you have Ninject DLLs into your drive, the first step is to add a reference to Ninject.dll in the library directory.

Add a new class to your project and call it SalutationService:

class SalutationService
{
    public void SayHello()
    {
        Console.WriteLine("Hello Ninject!")
    }
}

Add using Ninject to the using section of Program.cs. Add the following lines to Main method:

using (var kernel = new Ninject.StandardKernel())
{
    var service = kernel.Get<SalutationService>();
    service.SayHello();
}

This shows how Ninject works in a simple way. No special configuration or annotation is required separately. Ninject automatically injects and print the "Hello Ninject!"[1] for us as shown in the previous example.

Further details of Main method here, firstly, we created a kernel object by instantiating StandardKernel. Kernel is the starting point of creating dependency graph, and StandardKernel is the default implementation of such an object. In this example, the graph only consists of one type, SalutationService. We didn't call the constructor of SalutationService in the Main method. Instead, our container(kernel) does it automatically. Get method returned an instance of the given type we require. The Get method was provided with the root type(SalutationService) of our dependency graph and returned the graph object.

With Ninject[edit]

The most amazing part by using Ninject is that you don't need to spend time on doing the "busy work" of creating[4] and connecting objects by hand.

How Ninject constructs types[edit]

Ninjects calls one of the constructors, just like we would do Dependency Injection by hand. When asked to instantiate an object, Ninject looks at all the available public constructors and pick the one for which it knows how to resolve most of the parameters. which means, if we need to resolve and have dependencies injected to the service class, Ninject takes care of instantiating the objects.

Examples[5][edit]

Defined the ITaxCalculator interface and a trivial implementation TaxCalculator as follows:

decimal CalculateTax(decimal gross);
public class TaxCalculator : ITaxCalculator
{
    private readonly decimal _rate;
 
    public TaxCalculator(decimal rate)             
    {
        _rate = rate;
    }
 
    public decimal CalculateTax(decimal amount)
    {
        return Math.Round(_rate * amount, 2);
    }
}

Now, if any other class need to use the ITaxCalculator implementation to fulfill its responsibility, we can say that an implementation of ITaxCalculator is a dependency to them.

using (IKernel kernel = new StandardKernel())
{
    kernel.Bind<ITaxCalculator>()
          .To<TaxCalculator>()
          .WithConstructorArgument("rate", .2M);
 
    var tc = kernel.Get<ITaxCalculator>();
    Assert.Equal(20M, tc.CalculateTax(100M));
}

Through the interface, we instructed the kernel how to bind requests for ITaxCalculator to TaxCalculator class, passing tax rate to its constructor. Now, a Sale class models an ongoing transaction. The class depends on a ITaxCalculator to compute the final price of the shopping cart.

public class Sale
{
    private readonly ITaxCalculator taxCalculator;
 
    public Sale(ITaxCalculator taxCalculator)
    {
        this.taxCalculator = taxCalculator;
    }
 
    // more stuff....
 
    public decimal GetTotal()
    {
    // use the tax calculator to calculate the total
    }
}

Create the sale based on the preceding example:

kernel.Bind<ITaxCalculator>()
          .To<TaxCalculator>()
          .WithConstructorArgument("rate", .2M);
var sale = new Sale(kernel.Get<ITaxCalculator>());>

Or let Ninject to find out how a Sale should be built based on the binding information it received:

kernel.Bind<ITaxCalculator>()
          .To<TaxCalculator>()
          .WithConstructorArgument("rate", .2M);
var sale = kernel.Get<Sale>();

Ninject is able to build a Sale class to take care of fulfilling the dependencies behind the scenes.

External links[edit]

References[edit]

  1. ^ a b Baharestani, Daniel (2013). Mastering Ninject for Dependency Injection. PACKT.
  2. ^ "Ninject". CodePlex. Retrieved 2016-09-13.
  3. ^ "Component Based Architecture" (PDF).
  4. ^ "GitHub".
  5. ^ Ricciardi, Stefano. "Ninject Mini Tutorial".

Category:.NET