
Injecting a Business Component using Property (Setter) Injection
The presenter for the user interface, the class named StoplightPresenter, requires an instance of the class named Stoplight that represents the set of colors and methods of a real stop light. The Stoplight class uses an enumeration of the three colors (red, yellow, and green), exposes the Next method that the application can use to change the colors in a predefined sequence, and raises the StoplightChangedHandler event when a color change occurs. The argument for this event is an instance of class named LightChangedEventArgs that exposes the current color.
To obtain an instance of this class, the StoplightPresenter exposes it as a property and applies the Dependency attribute to the property, as shown in the following code.
private Stoplight stoplight;
[Dependency]
public Stoplight Stoplight
{
get { return stoplight; }
set { stoplight = value; }
}
Private _stoplight As Stoplight
<Dependency()> _
Public Property Stoplight() As StopLight.Logic.Stoplight
Get
Return _stoplight
End Get
Set(ByVal value As StopLight.Logic.Stoplight)
_stoplight = value
End Set
End Property
The dependent class type for dependency injection is the concrete class Stoplight, so the Unity container can create this object without requiring a mapping in the container.
The presenter also has a dependency on the StoplightSchedule class, which maintains references to the StoplightTimer and ILogger, exposes methods to update the durations for the colors and force a change to the next color, and responds to the OnTimerExpired event raised by the RealTimeTimer class.
To get a reference to a new instance of the StoplightSchedule class, the StoplightPresenter exposes it as a property named Schedule and applies the Dependency attribute to the property, as shown in the following code.
private StoplightSchedule schedule;
[Dependency]
public StoplightSchedule Schedule
{
get { return schedule; }
set { schedule = value; }
}
Private _schedule As StoplightSchedule
<Dependency()> _
Public Property Schedule() As StoplightSchedule
Get
Return _schedule
End Get
Set(ByVal value As Stoplight)
_schedule = value
End Set
End Property
Again, the dependent type is a concrete class, in this case the StoplightSchedule class, and so the Unity container can create this object without requiring a mapping in the container.