Blazor-Component inherits from BaseClass

Viewed 2628

i am about to create a Base-Class for my Razor-Components. This Base-Class looks like:

public abstract class ExampleBase : ComponentBase 
{
    public virtual void Submit()
    {
        //DoSomething
    }

    public virtual void Back()
    {
        //DoSomething else
    }
}

my Blazor-Component inherits from this class

@inherits ExampleBase

<button @onclick="Submit" />

So far so good, but when i start my App and this Page is about to Load then i receive an Exception:

[2020-09-29T12:09:03.920Z] Error: System.ArgumentException: The component type must implement Microsoft.AspNetCore.Components.IComponent. at Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder.OpenComponent(Int32 sequence, Type componentType)

what is wrong on being inherited from ComponentBase ?

Thanks for your help

Addition: I call my Razor-Component like this and the Exception throws at builder.OpenComponent

RenderFragment CreateFragment() => builder =>
{
  builder.OpenComponent(0, typeof(MyRazorComponent));
  builder.CloseComponent();
}

Hope this helps

1 Answers

First of all - Thank you all for you're help i really appreciate!

After a few hours break. I found my own mistake...

What i am doing: i've created a service which loads a List of Type List this service gets inject in a Razor-Component.

The code of service:

//this returns a listOfRazorComponents
return AppDomain.CurrentDomain.GetAssemblies()
            .Where(x => x.FullName.StartsWith("SampleApplication")).FirstOrDefault()
            .DefinedTypes.Where(x=>x.BaseType is ComponentBase);

In my Razor-Component i've displayed the List of Razor-Component which is returend by the service.

@page "/"
@inject MyService myService


@CurrentFragment

@code{

  private RenderFragment CurrentFragment { get; set; }
  private List<TypeInfo> listOfRazorComponents;
 
  protected override void OnInitialized
  {
     listOfRazorComponents = new List<TypeInfo>(myService.GetRazorComponents());
     CreateFragment(listOfRazorComponents[0]);
  }

  RenderFragment CreateFragment(Type typeToDisplay) => builder =>
  {
     builder.OpenComponent(0, typeToDisplay);
     builder.CloseComponent();
  };
}

Now my stupid mistake... After i added the @inherits ExampleBase to all of my Razor-Components the Components wasnt reconized by my "MyService" because i checked there for

x=>x.BaseType is ComponentBase 

this caused an empty List of Razor-Components and when i called CreateFragment(Type typeToDisplay) the typeToDisplay was null.

I really dont understand why builder.OpenComponent(0, null) does not throw an NullReferenceException. Thats confusing to me

such a stupid error by my self took me a lot nerves... hope this will prevent others to forget this :)

Related