Reputation: 27605
I have a class CalculationManager
which is instantiated by a BackgroundWorker
and as such has a CancellationRequested
property.
This CalculationManager
has an Execute()
method which instantiates some different Calculation
private classes with their own Execute()
methods which by their turn might or might not instantiate some SubCalculation
private classes, in sort of a "work breakdown structure" fashion where each subclass implements a part of a sequential calculation.
What I need to do is to make every of these classes to check, inside the loops of their Execute()
methods (which are different from one another) if some "global" CancellationRequested
has been set to true. I put "global" in quotes because this property would be in the scope of the topmost CalculationManager
class.
So, question is:
How can I make a property in a class visible to every (possibly nested) of its children?
or put down another way:
How can I make a class check for a property in the "root object" of its parent hierarchy? (well, not quite, since
CalculationManager
will also have a parent, but you got the general idea.
I would like to use some sort of AttachedProperty
, but these classes are domain objects inside a class library, having nothing to do with WPF or XAML and such.
Upvotes: 0
Views: 78
Reputation: 22074
Something like this ?
public interface IInjectable {
ICancelStatus Status { get; }
}
public interface ICancelStatus {
bool CancellationRequested { get; }
}
public class CalculationManager {
private IInjectable _injectable;
private SubCalculation _sub;
public CalculationManager(IInjectable injectable) {
_injectable = injectable;
_sub = new SubCalculation(injectable);
}
public void Execute() {}
}
public class SubCalculation {
private IInjectable _injectable;
public SubCalculation(IInjectable injectable) {
_injectable = injectable;
}
}
private class CancelStatus : ICancelStatus {
public bool CancellationRequested { get; set;}
}
var status = new CancelStatus();
var manager = new CalculationManager(status);
manager.Execute();
// once you set status.CancellationRequested it will be immediatly visible to all
// classes into which you've injected the IInjectable instance
Upvotes: 1