Under what circumstances use method callinjection
Automatic instantiation of dependent objects when the parent object is instantiated
Easy way to see the items that each class relies on in your code
The parent object has many constructors that are related to each other, resulting in inconvenient debugging and maintenance
The parent object contains a number of parameter constructors, especially if the parameter types are similar only through the position of the parameter
Hide dependent objects, not exposed as attributes
Control which objects can be injected without altering the parent object or application by modifying the dependent object's code
Preparatory work
public interface IPlayer
{
void Play();
}
public class Mp3Player : IPlayer
{
public Song mSong;
[InjectionMethod]
public void Init(Song song)
{
this.mSong = song;
}
public void Play()
{
Console.WriteLine(string.Format("{0}: Now Playing [{1}] Singing by ({2})", this.Name, this.mSong.Name, this.mSong.Singer));
}
public string Name
{
get
{
return "Mp3 Player";
}
}
}