I am building a reusable Razor class library for Blazor components.
I have an interface that any Blazor component could implement:
public interface IControllableComponent
{
void SetSomeValue(int someValue);
}
How can I get a List of all components that implement that interface?
public interface IControllableComponentManager
{
void SetSomeValueForAllControllableComponents(int someValue);
}
public class ControllableComponentManager : IControllableComponentManager
{
IList<IControllableComponent> _controllableComponentList;
public ControllableComponentManager()
{
_controllableComponentList = ??? // how to populate this list?
}
public void SetSomeValueForAllControllableComponents(int someValue)
{
foreach (var controllableComponent in _controllableComponentList)
{
controllableComponent.SetSomeValue(someValue);
}
}
}
I want for my reusable Razor class library to be used in the code behind in different projects:
public class MyControllableComponentBase : ComponentBase, IControllableComponent
{
protected int _someValue;
public void SetSomeValue(int someValue)
{
_someValue = someValue;
}
}
Is there a way to populate _controllableComponentList in ControllableComponentManager?
I would like to do this in a clean, proper way, without using reflection. Preferably in the style of ASP.NET Core with dependency injection.
The problem is that Blazor components are instantiated in Razor markup as <Component></Component> so I don't know how to get their references to add them to the List<>.
Assembly.GetTypes(). You can then filter those types by the interface they are implementing. Note that this is generally an expensive operation, so you should cache your results. - poke<Component></Component>I don't know how to get their references to add them to the list. - Jinjinov