Reputation: 40032
If one uses property injection how do you set properties on that type? For example
public class MyClass
{
public ITimer MyTimer {get;set;}
}
We can use DI to resolve ITimer but how/where do we define property values for ITimer, for example, if you want to set the Interval property where does this happen?
Thanks
Upvotes: 2
Views: 472
Reputation: 19881
Please clarify ...what do you mean by 'if you want to set the Interval property where does this happen?' If you are looking for when to set properties for ITimer, I prefer using a method for better readability and maintenance:
public class MyClass {
private ITimer timer;
public ITimer Timer {
get { return timer; }
set { SetDefaultTimer(value); }
}
private void SetDefaultTimer(ITimer timer) {
timer.Interval = 1000;
// other default properties
// assign
this.timer = timer;
}
}
I don't believe this will stop someone from altering the interval or other properties on the Timer. I don't know if that is your intent.
Update:
Depending on your ITimer interface, you could completely hide the Interval property which means that the interval could not be altered because of encapsulation. Exposing the interval property through encapsulation requires something like the following:
public interface ITimer {
int Interval {get; set;}
}
...exposes a way to set an interval value - e.g.:
public class MyTimer : ITimer {
Timer timer;
// implement ITimer member
public int Interval {
get { return timer.Interval; }
set { timer.Interval = value; }
}
}
If the interface did not define the property, there is no way to access the encapsulated timer properties outside of your controlled API (except maybe by reflection ...)
Hope that helps.
Upvotes: 0
Reputation: 57939
If you know that you want specific settings for an ITimer
that gets injected into MyClass
, you can do that work in the setter of the Timer
property.
public class MyClass
{
private ITimer _timer;
public ITimer Timer
{
get { return _timer; }
set
{
if(_timer = null && value != null && value.Interval == 0)
{
value.Interval = 5000;
}
_timer = value;
}
}
Really, constructor injection gives you a lot more flexibility for this sort of thing.
Upvotes: 3