Description
Blazor comes with some pretty nice tricks, some of them which were either not possible, or just hard to implement in other frameworks. Having a modular system in blazor is … amazingly easy. You just have to tell the Router component, to look for other assemblies also
I have a simple blazor app, that comes in with the template in Visual Studio. I added a Razor class type of project and in it I defined 2 files:
- One is the “_discovery” file which is an empty class that I am using just to reference it from the main app
- The other is a page with a simple text
In the App.razor file, you can see that the Router actually references the assembly where it looks for the page components. The Router component also has another attribute which accepts a list of other assemblies:
The module page has the page directive and the route is at /modulepage
And voila
Coool, right?
And it get’s cooler. How about we throw some reflection in? Let’s say, loading some modules from a json file. In this case the main project is not referencing the module project. Do not forget to copy the ModuleOne.dll file to the main bin folder (or create a post built event for that)
First define the module in app settings:
Then we create the ModuleDescriptor class
Now we just have to read the settings file, load the dll in memory and pass it to the router. Easy job
Don’t Work.
I get: Sorry, there’s nothing at this address.
(Router ->NotFound Section)
Perhaps the assembly you are trying to load is not found. Make sure that the assembly is discoverable.
How I make the assembly discoverable? Is this example Blazor Web Assembly or Blazor Server? I can´t make it work (second case, unreferenced assembly)
The example was made using Blazor Server side on .NET Core 2.2. There is nothing special about making an assembly “discoverable”. It’s just being read from the working directory (you have to compile the module and copy the dll, or make your own system of reading dll files from different projects)