Secret ingredients to quality software

SSW Foursquare

Rules to Better Blazor - 3 Rules

Blazor lets you build interactive web UIs using C# instead of JavaScript. Blazor apps are composed of reusable web UI components implemented using C#, HTML, and CSS. Both client and server code is written in C#, allowing you to share code and libraries.
Get started with Blazor here

  1. Prepare for the future of web development by checking out these Blazor learning resources.

  2. When creating Blazor components that communicate with web APIs it is often tempting to inject the HttpClient and use it directly to send requests. While this is quick and easy to accomplish, this tightly couples the component to the HttpClient and the specific implementation of the web API. The downside of this tight coupling is that the component cannot be easily refactored for breaking changes (e.g. routes, payloads, querystrings, auth, etc) then the blast radius of changes can be quite substantial. The problem grows even further if accessing the API from multiple components. Another downside is that the component is no longer unit testable. Integration tests will be necessary which will require more effort to implement.

    Following the Dependency Inversion Principle (DIP) from the SOLID principles means that we should favour coding towards an interface rather than concrete implementations.

    Using an abstract client interface to interact with a web API has multiple benefits. One major benefit is that the component is decoupled from the concrete implementation of the web API client. Decoupled Blazor components can be unit tested with a mock implementation of the web API client. The decoupled concrete implementation of the web API client can also be tested in isolation without any UI concerns, and the code is more reusable in that it could be packaged and reused in other applications without any code duplication.

    blazor decouple bad example
    Figure: Bad example - Component depends on HttpClient directly

    blazor decouple good example
    Figure: Good example - Component depends on web API client abstraction


  3. Do you share common types and logic?

    Due to Blazor using C#, your client and server can share the same model library - sharing behavior and data.

    This will reduce the amount of code you need to write, and make it easier to maintain.

    To share your classes between the client and server, just create a class library and reference it in your client and server projects.

    See as an example.


We open source. Powered by GitHub