I have following service:
public class Service
{
private List<Model> _modelList = new List<Model>();
public List<Model> Modellist
{
get { return _modelList ; }
private set
{
_modelList = value;
NotifyStateChanged();
}
}
public event Action OnChange;
public void NotifyStateChanged() => OnChange?.Invoke();
}
and normally used like:
protected override void OnInitialized()
{
_Service.OnChange += StateHasChanged;
}
But i want to make that generic, and get the event using reflection. I tried the following with no luck:
protected override void OnInitialized()
{
var backingField = Service.GetType().GetField("OnChange", BindingFlags.Instance | BindingFlags.NonPublic);
var delegateInstance = (Action)backingField.GetValue(Service);
delegateInstance += StateHasChanged;
}
How do I get this working?
Many Thanks!
@Xerillio is headed in the right direction I think, one option is to make your service generic BUT constrain it with an interface as discussed here, and use the interface to provide the contract for the OnChange
event. Reflection isn't required this way at all, and all implementations of the service now have to have the OnChange
event to subscribe to. (and unsubscribe from during teardown!)
Option 2 if you have a lot of methods and properties that you know you will need in every context, is to set up an abstract class or base class that allows you to inherit / override some of those methods and properties and adjust / extend implementation as you see fit. This would be up to you to dictate if it's appropriate, but still keeps you out of reflection.