Can I call this a dependency injection?

94 Views Asked by At

I am new to dependency injection and I am trying to figure it out. Lets say I have class book :

class Book
{
    public String Author { get; set; }
    public String Title { get; set; }
    private int Quantity {get;set;}

    public Book(String aut, String pav, int qua)
    {
        this.Author = aut;
        this.Title = pav;
        this.Quantity = qua;
    }
}

and then other class book with type

class BookWithType
{
    public Book Book { get; set; }
    public String Type { get; set; }

    public BookWithType(Book book, String type)
    {
        this.Book = book;
        this.Type = type;
    }
 }

Can I say that this is a dependency injection when in BookWithType constructor I inject Book object?

2

There are 2 best solutions below

4
On BEST ANSWER

You wouldn't create a dependency injection with a data transfer object. It would be more like:

public class Book
{
    public String Author { get; set; }
    public String Title { get; set; }
    public int Pages {get;set;}
    public string Type {get;set;}

    public Book(String aut, String pav, int pages, string type)
    {
        this.Author = aut;
        this.Title = pav;
        this.Pages = pages;
        this.Type = type;
    }
}

Then some kind of display layer like:

public class BookView
{
    private IBookRetriever _bookRetriever;

    public BookWithType(IBookRetriever bookRetriever)
    {
        _bookRetriever = bookRetriever;
    }
    public Book GetBookWithType(string type) {
        return _bookRetriever.GetBookOfType(type);
    }
}

Where IBookRetriever...

public interface IBookRetriever {
    Book GetBookOfType(string type);
}
0
On

The point of Dependency injection pattern is to create loosely coupled components without concrete dependencies on other components. So, what's wrong with using concrete implementations directly? Well, problem is that in future it could be difficult to support such systems. On the contrary, when you have loosely coupled classes, it's very easy to change their behaviour: you just need to provide another implementation of abstraction.

Christos gave your nice example of doing it. Your BookWithType class no longer depends on concrete Book, instead it depends on IBook abstraction. So, you could provide different implementation of IBook if needed. But you, probably, would not see the full power of using DI from this example, because it's rather simplified. Instead of this, imaging huge system with hundreds of components bonded together: how to fight complexity there? The answer is to use best programming practices, and DI is one on the top of them.

And most importantly, with loosely-coupled components you would get highly-testable system, where to write unit-tests is a pleasure: you could easily provide mocks/stubs etc instead of concrete implementations.

So, the answer on your question is "NO". You can't call this a dependency injection(within the meaning of "DI" pattern).