Reducing the
dependency between two or more classes by creating an Interface to its
respective classes and making loosely coupled architecture, this is called Inversion of Control. Here objects are created at run-time.
There are
some IOCs in market for .net: Ninject, Unity, Autofac etc
Dependency
injection will assign respective objects automatically.
There are
Constructor Injection Property Injection, Method injection etc. Commonly used
real-time injection is constructor injection.
Below is the
example for dependency injection:
Open visual
studio. Create new project [ I have selected Console application]
Go to Tools -> NuGet
Package Manager Console
In package
manager console, type: Install-Package Ninject
Internet
connection is mandatory to install the package; else you can manually add
reference of Ninject downloaded DLL.
Now we can
view the Ninject.dll in our solution reference.
Create an
Interface as below.
Below is the code for interface:
using System;
namespace DependencyInjectionExample
{
public interface IStaff
{
string getStaffDetails();
}
}
Screenshot:
Create class
file where we need to define the function.
Created a class as ‘TechnicalStaff’ and inherits the interface ‘IStaff’ as below:
using System;
namespace DependencyInjectionExample
{
public class TechnicalStaff : IStaff
{
public string getStaffDetails()
{
return "19 Technical
staff";
}
}
}
Screenshot:
Create a new class as
Employee as sown below:
Place the below code
in the employee class.
using System;
namespace DependencyInjectionExample
{
public class Employee
{
private readonly IStaff staf;
public Employee(IStaff staffing) //creating contructor
{
staf = staffing; //Inversion of
control
}
public string Getdetails()
{
return staf.getStaffDetails();
}
}
}
screenshot:
Now coming into program.cs file, we
need to add namespaces of Ninject.
using Ninject;
using Ninject.Modules;
Below is the complete code for
Program.cs:
using System;
using System.Text;
using Ninject;
using Ninject.Modules;
using System.Reflection;
namespace DependencyInjectionExample
{
class Program
{
static void Main(string[] args)
{
var kernel = new StandardKernel();
kernel.Load(Assembly.GetExecutingAssembly());
var details = kernel.Get<IStaff>();
var employee = new Employee(details);
string result = employee.Getdetails();
Console.WriteLine(result);
Console.ReadKey();
}
}
public class DependInj : NinjectModule
{
public override void Load()
{
Bind<IStaff>().To<TechnicalStaff>();
}
}
}
In the above
code, we can see that TechnicalStaff.cs
and Employee.cs doesn’t have any
direct communication. Interface plays a key role. Sending the interface as a parameter
for constructor defines the Inversion of Control.
OUTPUT :