Skip to main content

How to implement Dependency Injection Using Ninject


When i was a little young at programming, i have always wondered, why the need for dependency injection, why the need for creating more work for yourself by creating objects and injecting it to the constructor of the dependent object, where you can instantiate the object directly from your codebase, not until i realised the importance, i’m sure some cool developer are asking some of this questions that i once asked, in this article i intend to answer some of this question and also show some quick implementation of dependency injection with Ninject.
According to Wikipedia, the intent behind dependency injection is to decouple objects to the extent that no client code has to be changed simply because an object it depends on needs to be changed to a different one.
The main aim here is to adopt a modular design approach, where there are lots of small blocks loosely coupled with each block knows very little about its neighbour other than how it connects to them, this approach greatly helps in testing and maintenance of the code base, as each blocks can be independently tested and replaced without breaking the functionality of other modules.

Implementing Dependency Injection with Ninject
Ninject it’s an open source dependency injector for .NET.  it’s available on Nugget. For DI container to be useful for creating objects and injecting them in the constructors, and control the lifetime of those objects, the container needs to available for the whole duration of the application running.

Container Bindings
This process involves binding interface to corresponding implementation so they can be resolved at run time.

public interface ICar
{
     String Car { get; }
}








public class CarAdapter : ICar
{
  public String Car
  {
     get { return “Red”; }

  }
}



Configuring the dependency bindings

The purpose of this configuration is to make that DI container created during application startup remains in memory until application shut down.

public class ConfiguringNinject
{

public void Configure(IKernel container)
{
container.Bind<Icar>().To<CarAdapter>().InRequestScope();

}

}


Dependency Resolver for Ninject

This will resolve all dependencies required at run time the dependent object. This is what allows to push dependencies to the constructor of the dependent objects.




public sealed class DependencyResolver : IDependencyResolver
{
private readonly IKernel _container;

public DependencyResolver(IKernel container)
{
_container = container;

}
public IKernel Container
{
get { return _container; }

}

public object GetInstance(Type instanceType)
{

return _container.TryGet(instanceType);

}

public IEnumerable<object> GetInstances(Type instanceType)
{
return _container.GetAll(instanceType);
}

public IDependencyScope BeginScope()
{
return this;
}

public void Dispose()
{
  GC.SuppressFinalize(this);
}
}




Summary


Dependency injection is a great approach that contributes to making sure that our code base is loosely coupled. The benefit of loosely coupled code base is much, but among them is clean and efficient unit testing, it makes unit testing clean and efficient.

Comments

Popular posts from this blog

How to implement RESTful API Versioning in ASP.NET Web API 2 using IHttpRouteConstraint

The only thing constant in life is change, and that is proved everyday in our industry, API’s are cool to extend the functionality of your application and expose it to other developers. The cool thing about IT and software, it’s that things changes quite rapidly and so it’s the technology, hence technology can change and the needs of your organisation can change, hence in order to keep serving this evolving needs and keep been relevant, your api might need to change also. Small changes can be accommodated within the initial version, but changes that will risked breaking the existing code, will required the need for versioning.

Implementing a custom IHttpRouteConstraint

According to msdn, a IHttpRouteConstraint simply Represents a base class route constraint. What then is a route constraint? A route constraint simply gets or sets a dictionary of expressions that specify valid values for a URL parameter.

publicclassApiVersionRouteConstraint : IHttpRouteConstraint
  {

publicApiVersionRouteCo…

How to implement multi-tenancy with subdomains using Route Constraint in ASP.NET MVC

According to Wikipedia, The term "software multitenancy" refers to a software architecture in which a single instance of software runs on a server and serves multiple tenants. A tenant is a group of users who share a common access with specific privileges to the software instance. With a multitenant architecture, a software application is designed to provide every tenant a dedicated share of the instance - including its data, configuration, user management, tenant individual functionality and non-functional properties. Multitenancy contrasts with multi-instance architectures, where separate software instances operate on behalf of different tenants. By giving companies, access to a tenant through a subdomain of choice, will help to personalise the experience more and gives a sense of ownership to each tenant. This will go along way to bring consistency in there branding.
Implementing Route Constraint
You use route constraints to restrict the browser requests that match a partic…

How Wrong Use of Data Structure is Costing You Performance

Data structure is a specialise way of storing and organising data so that it can be access efficiently. Today a good chunk of our codes makes use of data structure, and the importance of using the proper data structure for the right job cannot be over emphasised. There are many types of data structure, each one designed to handle the storing and manipulation of data in a specific way. The trick here now is, knowing how to use data structure is not enough but knowing the type to use that’s suits your operation without sacrificing performance.  The determinant factor of the right data structure to use in your program is dependent on some factor like the type of operation you want to perform on the data set like Searching, addition, deletion and access by index.

Comparison between Basic Data Structures

Data Structure Addition Search Deletion Access by Index Array(T[]) O(N) O(N) O(N) O(1) LinkedList(LinkedList<T>) O(1)