Julian
What is Dependency Injection and provide example?
By Julian in .NET on Feb 08 2017
  • Julian
    Feb, 2017 8

    DI is providing an object what is required at runtime. So that the object is not dependent on any other object instance. This helps creating code that is more manageable and testable.Example: Say I have a Car object which is dependent on Wheel. So if I create the Car class as: public Car() {Wheel w = new Wheel(); } The above code is fully dependent on Wheel Object. What happens if there are several versions of wheel to be tested.Using the concept of DI we can create the Car class like : public Car(IWheel wheel) {this.wheel = wheel; } Now we can create any type of wheel and inject its instance while creating the Car.

    • 16
  • Emamul Hasan
    Feb, 2017 27

    Dependency Injection is a software design pattern that allow us to develop loosely coupled code. DI is a great way to reduce tight coupling between software components. DI also enables us to better manage future changes and other complexity in our software. The purpose of DI is to make code maintainable.The Dependency Injection pattern uses a builder object to initialize objects and provide the required dependencies to the object means it allows you to "inject" a dependency from outside the class.

    • 9
  • Prakash Tripathi
    Mar, 2017 6

    Before DI, let's first understand IOC. Inversion of Control (IOC) is a generic term that means objects do not create other objects on which they rely to do their work. Instead, they get the objects that they need from an outside source.One of the analogy is Hollywood Principle i.e. Don’t call us, we’ll call you!! DI is a form of IOC or an implementation to support IOC or subset of IOC, where dependencies are passed through constructors/ setters/ methods/ interfaces.If this helps to address the issue, please close the thread by accepting the answer.

    • 7
  • Satyaprakash Samantaray
    Feb, 2017 9

    The process of removing dependency of objects which makes the independent objects. It is used in TDD.It Increases code reusability. It Improves code maintainability.

    • 6
  • Nilesh Shah
    Mar, 2017 2

    Dependency injection means instead of leaving it to the user to create the dependent objects required by any other object, they are taken care of automatically. You will need an Inversion of Control container to take care of the dependencies of an object so it can be created without passing all its required dependencies.

    • 3
  • Brajesh Kumar
    Feb, 2017 25

    Here's a common example. You need to log in your application. But, at design time, you're not sure if the client wants to log to a database, files, or the event log.So, you want to use DI to defer that choice to one that can be configured by the client.This is some pseudocode (roughly based on Unity):You create a logging interface:public interface ILog {void Log(string text); } then use this interface in your classespublic class SomeClass {[Dependency]public ILog Log {get;set;} } inject those dependencies at runtimepublic class SomeClassFactory {public SomeClass Create(){var result = new SomeClass();DependencyInjector.Inject(result);return result;} } and the instance is configured in app.config:

    • 3
  • Hamid Khan
    Aug, 2017 21

    Dependency Injection means passing something that allow the caller of a method to inject dependent objects into the method when it is called. For example if you wanted to allow the following piece of code to swap SQL providers without recompiling the method: We can pass dependency in following ways 1- Constructor level 2- Method level 3- Property level There are following advantages of DI1- Reduces class coupling2-Increases code reusing 4- Improves code maintainability 5- Improves application testing Example: public interface IEmployeeService{ void SaveEmployee();} public class EmployeeService : IEmployeeService{ public void SaveEmployee() { //To Do: business logic }} public class Client{ private IEmployeeService _employeeService; public Client(IEmployeeService employeeService) { this._employeeService = employeeService; } public void Start() { this._EmployeeService. SaveEmployee (); } } ______________________________________class Program{ static void Main(string[] args) { Client client = new Client(new EmployeeService()); client.Start(); Console.ReadKey(); } } Dependency Injection is basically to reduce coupling between the code. The caller can call the object without modifying the method it's calling .

    • 1
  • pankaj rai
    May, 2017 19

    In Dependency Injection design pattern, we does not care about creation of Object . Object is automatically created by IO Container assigned to object

    • 1
  • Govind Mishra
    May, 2019 21

    You can see DI advantage in the .net core that how we can use it and implement

    • 0
  • Suresh Kumar
    Nov, 2017 3

    public class Customer {private IStorageHelper helper;public Customer(){helper = new DatabaseHelper();}...... }public class Customer {private IStorageHelper helper;public Customer(IStorageHelper helper){this.helper = helper;}...... }public class HomeController : Controller {ICustomerRepository repository = null;public HomeController(ICustomerRepository repository){this.repository = repository;}public ActionResult Index(){List data = repository.SelectAll();return View(data);} } public interface ICustomerRepository {List SelectAll();CustomerViewModel SelectByID(string id);void Insert(CustomerViewModel obj);void Update(CustomerViewModel obj);void Delete(CustomerViewModel obj); } public class CustomerViewModel {public string CustomerID { get; set; }public string CompanyName { get; set; }public string ContactName { get; set; }public string Country { get; set; } } public class MyControllerFactory:DefaultControllerFactory {private Dictionary> controllers;public MyControllerFactory(ICustomerRepository repository){controllers = new Dictionary>();controllers["Home"] = controller => new HomeController(repository);}public override IController CreateController(RequestContext requestContext, string controllerName){if(controllers.ContainsKey(controllerName)){return controllers[controllerName](requestContext);}else{return null;}} }public class ControllerFactoryHelper {public static IControllerFactory GetControllerFactory(){string repositoryTypeName = ConfigurationManager.AppSettings["repository"];var repositoryType = Type.GetType(repositoryTypeName);var repository = Activator.CreateInstance(repositoryType);IControllerFactory factory = new MyControllerFactory(repository as ICustomerRepository);return factory;} }... protected void Application_Start() {AreaRegistration.RegisterAllAreas();RouteConfig.RegisterRoutes(RouteTable.Routes);ControllerBuilder.Current.SetControllerFactory(ControllerFactoryHelper.GetControllerFactory()); }

    • 0
  • Suresh Kumar
    Nov, 2017 3

    public class Customer {private IStorageHelper helper;public Customer(){helper = new DatabaseHelper();}...... }public class Customer {private IStorageHelper helper;public Customer(IStorageHelper helper){this.helper = helper;}...... }public class HomeController : Controller {ICustomerRepository repository = null;public HomeController(ICustomerRepository repository){this.repository = repository;}public ActionResult Index(){List data = repository.SelectAll();return View(data);} } public interface ICustomerRepository {List SelectAll();CustomerViewModel SelectByID(string id);void Insert(CustomerViewModel obj);void Update(CustomerViewModel obj);void Delete(CustomerViewModel obj); } public class CustomerViewModel {public string CustomerID { get; set; }public string CompanyName { get; set; }public string ContactName { get; set; }public string Country { get; set; } } public class MyControllerFactory:DefaultControllerFactory {private Dictionary> controllers;public MyControllerFactory(ICustomerRepository repository){controllers = new Dictionary>();controllers["Home"] = controller => new HomeController(repository);}public override IController CreateController(RequestContext requestContext, string controllerName){if(controllers.ContainsKey(controllerName)){return controllers[controllerName](requestContext);}else{return null;}} }public class ControllerFactoryHelper {public static IControllerFactory GetControllerFactory(){string repositoryTypeName = ConfigurationManager.AppSettings["repository"];var repositoryType = Type.GetType(repositoryTypeName);var repository = Activator.CreateInstance(repositoryType);IControllerFactory factory = new MyControllerFactory(repository as ICustomerRepository);return factory;} }... protected void Application_Start() {AreaRegistration.RegisterAllAreas();RouteConfig.RegisterRoutes(RouteTable.Routes);ControllerBuilder.Current.SetControllerFactory(ControllerFactoryHelper.GetControllerFactory()); }

    • 0
  • Suresh Kumar
    Nov, 2017 3

    Dependency Injection (DI) is a design pattern that takes away the responsibility of creating dependencies from a class thus resulting in a loosely coupled system. In order to understand DI you need to be aware of the following terms: -Dependency -Dependency Inversion Principle -Inversion of Control (IoC)

    • 0
  • Lalit Raghav
    Aug, 2017 8

    Hi kindly find example of DIthis is tightly coupled class example class TeachingMath{public TeachingMath(){}public void teaching(){Console.WriteLine("Math teaching");}}class TeachingHindi{public TeachingHindi(){}public void teaching(){Console.WriteLine("Hindi teaching");}}class TeachingEnglish{public TeachingEnglish(){}public void teaching(){Console.WriteLine("English teaching");}}class Teaching{TeachingEnglish eng = new TeachingEnglish();TeachingHindi hindi = new TeachingHindi();TeachingMath math = new TeachingMath();public void TeachingClass(string[] subjects){foreach(string subject in subjects){if (subject=="English"){eng.teaching();}if (subject == "Hindi"){hindi.teaching();}if (subject == "Math"){math.teaching();}}}}public class Demo{public static void Main(){Teaching teaching = new Teaching();string[] subject={"Hindi","English"};teaching.TeachingClass(subject);Console.ReadKey(); }}----------------------------------------------------------------------------------------- Now we using DI with this example interface ITeaching{void teaching();}class TeachingMath:ITeaching{public TeachingMath(){}public void teaching(){Console.WriteLine("Math teaching");}}class TeachingHindi : ITeaching{public TeachingHindi(){}public void teaching(){Console.WriteLine("Hindi teaching");}}class TeachingEnglish : ITeaching{public TeachingEnglish(){}public void teaching(){Console.WriteLine("English teaching");}}class Teaching{public void TeachingClass(ITeaching[] subjects){foreach (ITeaching subject in subjects){ITeaching tesching = subject;tesching.teaching();}}}class Program{static void Main(string[] args){ITeaching[] te={new TeachingEnglish(),new TeachingHindi()};Teaching tech = new Teaching();tech.TeachingClass(te);Console.Read(); }}

    • 0


Most Popular Job Functions


MOST LIKED QUESTIONS