0

Im trying to understand Dependency Injection. I have created a sample example for this . Can any one please tell ,is this example correct or not

public interface IEngine
    {
        void Start();
        void SayHelloFromEngine();
    };
    public class Engine :IEngine
    {
        public Engine(){
        }
        public void Start()
        {
            Console.Write ("Hey it is started");
        }
        public void SayHelloFromEngine()
        {
            Console.Write ("Hello from Engine");
        }
    }
    public class Car 
    {
        private readonly IEngine _engine;
        public Car(IEngine engine){
            _engine=engine;
            _engine.SayHelloFromEngine ();
        }

    }

and my object creation would be

Car car2 = new Car (new Engine ());

Please guide me on what steps i'm doing wrong.

YCF_L
  • 49,027
  • 13
  • 75
  • 115
Sahithi
  • 83
  • 9

2 Answers2

0

You example looks good to me. That's pretty much how I tend to structure things.

There is a good stack overflow thread here with some useful links and posts.

The thing to work on I guess, is how you create the implementations and managing your dependencies. You can create your own factory classes/methods to do it, or use an existing framework, something like Ninject.

Community
  • 1
  • 1
Alex McNair
  • 121
  • 5
0

It's common to add a guard clause to your constructors that take dependencies, so that you can throw an exception immediately if someone tries to pass in a null dependency.

public class Car 
{
   private readonly IEngine _engine;
   public Car(IEngine engine)
   {
      if (engine == null)
      {
         throw new ArgumentNullException("engine");
      }
      _engine=engine;
      _engine.SayHelloFromEngine ();
   }
}  

A big part of dependency injection is how you create your dependencies. When you say Car car2 = new Car (new Engine ());, you're hard coding your dependency, which is kind of defeating the purpose of dependency injection. You should have a single composition root where all of your dependencies are defined. If you're not sure whether you're doing something correctly, a good rule of thumb is that you should not be newing any of your dependencies anywhere.

One more thing; when you're composing your dependencies, make sure you don't fall into the trap of making a service locator.

Community
  • 1
  • 1
Ben Rubin
  • 5,557
  • 3
  • 24
  • 50