Blazor Basics: A Beginner’s Guide to Blazor Architecture

Karishma Sheth
Simform Engineering
9 min readMay 25, 2023

An overview of Blazor Architecture: Components, advantages, and limitations.

With so many platforms and technologies available today for web development, it can be challenging for dev teams to choose which frameworks to incorporate into their projects. A team working on building a completely operational .NET web application needs front-end developers with expertise in front-end frameworks as well as developers proficient in #C for the backend.

To eliminate the need for two different groups of devs, you can consider using Blazor, a web framework that allows you to use the same talent for both front-end and back-end tasks. Developers can build web apps using their current C# skills and codebase from other .NET platforms as well, eliminating the need for separate teams for web and non-web development.

What is Blazor?

Blazor is a web framework developed by Microsoft that allows developers to build interactive web applications using C# instead of JavaScript. Blazor offers a component-based design, which implies that applications are created by assembling reusable components that may be combined to build complex user interfaces.

  • With Blazor, we can create components using C# and HTML and reuse them to build our web application.
  • Data binding and dependency injection are additional features offered by Blazor, which make it simple to create full-size applications with minimal code.

Why use Blazor?

The necessity for Blazor stems from the fact that JavaScript, the most extensively used language for developing web apps, has certain shortcomings, which include:

Debugging: Debugging JavaScript may be a challenging task, especially for large applications.

Performance: JavaScript can be slow, especially for complex applications.

Security: JavaScript is vulnerable to cross-site scripting (XSS), which can compromise web application security.

With Blazor, developers can build web apps using C#, a language that is more comfortable for .NET developers and has advantages like improved performance and efficient debugging tools. The advantages of using Blazor are as below:

Client-Side Web Development: Using Web Assembly, Blazor enables developers to create web apps that operate solely on the client side. This implies that web apps can be created in C# rather than JavaScript, which can be advantageous for developers who are more familiar with C#.

Code Reusability: By enabling code reuse between client-side and server-side apps, Blazor helps developers cut expenses and time spent on development.

Improved Performance: Contrary to conventional JavaScript-based web applications, Blazor’s usage of WebAssembly provides much faster page loads and enhanced performance.

Familiarity with .NET: Developers already familiar with .NET and C# can pick up Blazor fast and start building web apps.

Simplified Development: Blazor’s component-based design and data binding capabilities simplify web application development, allowing you to create sophisticated applications with less code.

Blazor architecture

Let’s talk about what the Blazor architecture is made of.

Blazor Components: Components form the foundation of the Blazor architecture, which are reusable units of UI. These can be written using C# and HTML markup or using Razor syntax, which lets developers write C# code right within HTML. It can comprise attributes, methods, and events, which can be used to build a more complicated UI.

Below is the sample code for a Blazor component:

// UserCardComponent.razor
<h1>User Details</h1>
<h3>@Name </h3>
<h3>@ID </h3>
<h3>@Email</h3>

@code {
[Parameter]
public string Name {get; set;}
[Parameter]
public int ID {get; set;}
[Parameter]
public string Email {get; set;}
}

Here, “UserCardComponent.razor” is the component that just displays all the fields that can be set through parameters. We can use this component in other Blazor pages as below:

//MyPage.razor
<UserCardComponent ID="124" Email="JohnDoe@domain.com" Name="John Doe"></UserCardComponent>

This will render the UserCardComponent with all the user fields, like Id, Name, and Email.

Rendering: Once the components are defined, Blazor renders them to the virtual DOM, which is lightweight compared to the actual DOM. When the application’s state changes, Blazor compares the previous virtual DOM with the current one and updates only the part of the DOM that needs to be changed. This, in turn, improves performance and reduces the amount of data to be transferred between server and client.

Hosting Models: Blazor supports two hosting models: server-side hosting and client-side hosting. In server-side hosting, Blazor components are executed on the server, and the UI is rendered in the browser using SignalR to send updates to the client. In client-side hosting, the Blazor app, its dependencies, and .NET runtime are downloaded to the browser, and the app is executed directly on the browser UI thread.

1. Blazor Web Assembly (WASM)

Blazor WebAssembly is a client-side web development framework for building interactive web apps using C# instead of Javascript. These applications are executed directly in the browser, so they don’t require a server to render the UI.

  • The diagram below shows the architecture of Blazor WebAssembly and how client-side code interacts with the server-side code:
  • Since the code for Blazor WebAssembly is executed directly on the browser, these applications can be more secure than traditional ones which depend on sending responses to the client. Also, as C# is a strongly typed language, it will prevent common programming errors.
  • It can run on any device which supports modern browsers, like desktops, mobile devices, and IOT devices. This can reduce development costs and increase the reach of the application.
  • After the program is downloaded from the server, there is no dependency on .NET server-side. Therefore, the app stays functioning even if the server goes down.

However, there are a few drawbacks as well to keep in mind while working with Blazor WebAssembly:

  • Almost all modern browsers support WebAssembly, but some older browsers may not support it, reducing the reach of the applications.
  • These applications will be larger in size since they include all the .NET runtime and libraries. It takes a lot of time to load the application initially. This is called “cold start time,” which is usually much more than the traditional web application.
  • .NET has a wide variety of libraries available, but not all of those are compatible with Blazor WebAssembly.

In all, Blazor WebAssembly offers an adaptable development framework that allows you to create quick, secure and modern applications using familiar technology.

2. Blazor Server

  • Unlike Blazor WebAssembly, Blazor Server executes the application on the server and then sends the UI updates to the client side using a SignalR connection.
  • The diagram below illustrates the Blazor server-side architecture:

As you can see from the above diagram, the Blazor server consists of various components:

Client Browser: Over a SignalR connection, the client browser communicates with the server to submit requests and receive UI changes.

SignalR Connection: The SignalR connection is used to send UI changes from the server to the client.

Blazor Server Application: On the server, the Blazor Server application performs all application logic and state management.

UI Components: The C# UI components are responsible for rendering the UI on the client side.

.NET Runtime: The server’s application code uses the .NET runtime.

ASP.NET Core Host: Hosting the Blazor Server application and granting access to the .NET runtime are the responsibilities of the ASP.NET Core Host.

  • Using Blazor server, you can provide real-time communication between client and server, providing a fast and responsive UI using the popular and widely used programming framework, i.e., NET.
  • Since all application logic and state management are performed on the server, Blazor Server applications can easily expand to support several concurrent users, which makes it easy to manage large applications. As a result, some common security flaws can also be prevented, like cross-site scripting (XSS) and cross-site request forgery (CSRF).
  • In addition, it also provides benefits for a rich user interface development due to its component-based architecture, which in turn provides reusability.

However, there are some disadvantages that developers should be aware of while working with Blazor server applications:

  • Since a stable network connection between the client and the server is required for Blazor Server, users in areas with poor network connectivity may experience slowness. Additionally, the app stops functioning if the client loses connectivity.
  • As the application increases in size and complexity, controlling the state may become more difficult since the UI state is saved on the server. Due to this, we may need to carefully manage the state to ensure responsiveness and scalability.
  • Blazor Server applications depend on the browser to handle user input and events. This means that some older browsers may not support all the features of Blazor Server applications.

In brief, Blazor Server is a server-side solution that uses SignalR to provide real-time communication between the client and the server. The UI is rendered on the server and sent to the client over a network connection, which means that Blazor Server applications can run on various devices and browsers.

Check out the code in the repository below, where you will find separate projects for Web Assembly and Server that are basic enough to give you a fundamental grasp of both hosting models.

Click here to check the code for Blazor Sample Apps

Communication: Depending on the hosting model, Blazor communicates with the server and the client in a number of ways. In server-side hosting, the client uses SignalR to send messages to the server, and the server adjusts the UI and sends updates back to the client. In client-side hosting, the client connects with the server directly via WebSockets or HTTP calls.

State Management: State, in Blazor, refers to the data that determines the application’s behavior and user interface. It provides both server-side and client-side state management options. Client-side state management stores the state on the client, whereas server-side state management stores it on the server. Blazor components may connect with one another via parameters and events, and developers can design stateful services that can maintain state over many components or the whole application.

Below is the sample code that illustrates the state:

<h1>@Title</h1>

<p>Count: @Count</p>
<button @onclick="IncrementCount">Increment</button>

@code {
[Parameter] public string Title { get; set; }
private int Count { get; set; } = 0;
private void IncrementCount()
{
Count++;
}
protected override void OnInitialized()
{
base.OnInitialized();
Console.WriteLine("Component initialized");
}
protected override void OnParametersSet()
{
base.OnParametersSet();
Console.WriteLine("Parameters set");
}
protected override void OnAfterRender(bool firstRender)
{
base.OnAfterRender(firstRender);
Console.WriteLine("Component rendered");
}
}

Explanation: In the above code, the count property is used to store the state of the component. Whenever the Count property is changed, the component will re-render to update the UI. In addition, we override three lifecycle methods (OnInitialized, OnParametersSet, and OnAfterRender) to demonstrate how the component lifecycle works.

Conclusion:

To summarise, Blazor is a modern web development framework that provides developers with two different architecture options: Blazor Server and Blazor WebAssembly. Blazor Server leverages SignalR to communicate between the client and the server in real-time, whereas Blazor WebAssembly allows developers to run C# code in the browser. The exact need of the application determines the hosting model to be used, and each model has benefits and drawbacks of its own.

Overall, Blazor is a powerful and versatile framework that simplifies web development by using C# expertise and offering a variety of tooling choices.

What to do next?

Once you have a good knowledge of how each of the Blazor models behaves on its own, you may attempt the following to develop your skills further:

Implement routing: Blazor supports client-side and server-side routing, which allows you to define URLs for different pages and components within your application.

Interact with APIs: Blazor makes it easy to interact with APIs using standard HTTP requests. You can use libraries like HttpClient to make requests and handle responses from APIs.

Add authentication and authorization: Blazor provides built-in support for authentication and authorization, allowing you to secure your application with user accounts and roles.

Use data binding: Blazor supports data binding, which allows you to bind data from your component to the UI, and vice versa. This makes it easy to build responsive and interactive UIs.

Use third-party libraries: Blazor is built on .NET, which means you can use any .NET library in your application. There are also several Blazor-specific libraries available, such as Blazorise and Radzen.

Create custom middleware: Blazor is built on top of ASP.NET Core, which means you can use middleware to intercept and handle requests and responses. This can be useful for implementing custom authentication or other functionality.

Use dependency injection: Blazor supports dependency injection, which allows you to easily inject dependencies into your components and services. This makes it easier to manage and test your application’s code.

Deploy to different environments: Blazor can be deployed to different environments, such as Azure, AWS, or other cloud providers. You can also deploy Blazor as a standalone application or as part of an existing ASP.NET Core application.

Happy Coding!

Stay ahead of the curve - Follow Simform Engineering blogs for the latest trends and developments updates.

--

--