carlosdubusm
carlosdubusm

Reputation: 1083

Dependency Injection with repositories

Suppose I have an AlbumRepository class (albums table) and SongRepository class (songs table).

An album has several songs.

This is the album class (pseudo code)

class Album{
    protected Title;
    protected AlbumID;
    protected Metadata;

    public Song[] getSongs(){
        SongRepository songRepository = new SongRepository();
        return songRepository.whereAlbumID(this.AlbumID);
    }
}

I want to refactor this code so it doesn't instantiate SongRepository inside getSongs method,, but how do I do that?

I could require SongRepository in the getSongs method....

public Song[] getSongs(SongRepository songRepository){
    return songRepository.whereAlbumID(this.AlbumID);
}

But I would really like to have getSongs with no parameters.

Should I inject SongRepository in the Album constructor?

But then if someone uses an Album object without calling getSongs, then there is no need for SongRepository at all...

I guess the question is Where should I inject SongRepository so the Album can use it?

Upvotes: 0

Views: 37

Answers (1)

Lilshieste
Lilshieste

Reputation: 2754

SongRepository is a dependency of Album. As such, DI tells us that Album should not instantiate it directly, but rather be supplied with it. And since Album cannot function properly without a SongRepository, it should require an instance to be provided to its constructor (as you suspected).

As for code that uses an Album without calling getSongs - why would that be a problem? The code that uses an Album shouldn't be the same code that instantiate the Album (object creation is a responsibility that should be delegated to the composition root).

Upvotes: 1

Related Questions