Blazor Implementations Throughout Internet & Native


Blazor can drive UI/UX throughout internet and native platforms, however implementations can range.

Blazor is consuming the world. .NET builders have understandably been enthusiastic about Blazor—a contemporary internet framework permitting for C# code back and front. Blazor can run server-side or fully client-side with WebAssembly, and the Blazor element/rendering
mannequin conjures up confidence with stability and extensibility.

With .NET Multi-platform App UI (.NET MAUI), Blazor goodness just isn’t confined to simply internet apps, however now very welcome on native cross-platforms apps for cell and desktop. Although Blazor parts/types can render the identical consumer interface (UI) throughout
internet, desktop and cell, the consumer expertise (UX) shouldn’t be the identical. In actual fact, builders will wish to have the pliability to do various things with Blazor throughout varied platforms. Let’s discover how a single shared codebase permits Blazor
code to have various implementations throughout platforms—sharing throughout variations is caring.

PS: This text is part of the C# Creation Calendar, run by Matthew Groves and Calvin Allen. Tune in for great .NET/C# content material on a regular basis main as much as Christmas!

Blazor With .NET MAUI

Blazor is the free, open-source and far beloved internet framework for constructing fashionable internet apps. Builders desirous to steer clear of
JavaScript can leverage the ability of .NET, C# and fashionable tooling to construct interactive stunning internet apps. The Blazor element mannequin, rendering engine and styling mechanisms provide flexibility—Blazor apps can run server-side in ASP.NET Core
or absolutely client-side with WebAssembly.

.NET MAUI is the evolution of .NET cross-platform technique—a brand new framework for creating native cell and desktop apps with C#/XAML. Nonetheless,
.NET MAUI brings in one thing magical known as the BlazorWebView element—an abstraction that finds evergreen browsers on respective platforms and permits for rendering of internet artifacts inside the shell of native apps.

Blazor and .NET MAUI are nearly made for one another, sharing the precise .NET runtime—.NET 6 yesterday and .NET 7 at the moment. Blazor apps can now be simply hosted inside .NET MAUI apps, with full native platform integration. Blazor Hybrid apps, as
they’re known as, allow lots of code sharing throughout internet and native apps on cell/desktop.

Shared Codebase

There are templates to get builders began utilizing Blazor with .NET MAUI—the ensuing challenge brings in Blazor internet artifacts inside .NET MAUI native apps. Whereas useful, a extra practical state of affairs is for builders to maintain sustaining internet apps
constructed with Blazor, whereas serving up the identical UI on native .NET MAUI apps. That is doable by bringing in Blazor internet tasks (server/shopper/each) and .NET MAUI tasks with Blazor—underneath a single answer, so Blazor runs in every single place from shared codebase.

Finder menu for Solution has BlazorEverywhere with entries below it for BlazorForNative which is bolded, BlazorForWeb.Client, BlazorForWeb.Server, BlazorForWeb.Shared, BlazorSharedUI

The objective, nevertheless, just isn’t reinventing the wheel—the identical Blazor parts and types ought to energy UI for internet and native apps. The trick is to maneuver the shared items out of the Blazor internet or .NET MAUI tasks right into a referenced shared class
library.

Circled under BlazorSharedUI are Pages with Counter.razor and Index.razor; Shared with MainLayout, NavMenu and SurveyPrompt; and wwwroot with css, which contains bootstrap folder, open-iconic folder and app.css

Platform Variations

It’s a terrific story to have shared Blazor parts/types drive frequent UI throughout internet and native apps. Nonetheless, an internet browser and platforms like iOS/Android/Home windows/macOS are very completely different type elements—and the UI/UX ought to possible not
be the identical.

Blazor can energy related experiences on the net—faucet into JavaScript goodness as wanted or assist internet hosting fashions on server/shopper. Whereas operating on native
cell/desktop apps by .NET MAUI, Blazor can do some very platform-specific issues.

Backside line is internet and native apps are completely different canvases—regardless that the shared UI is powered by Blazor, the implementations ought to range. So what’s known as for from a shared codebase is a typical API floor for consumption, with platform-specific
variations in implementations. Sounds very very similar to what a key programming metaphor is constructed for—yup, interfaces.

Interfaces Assist

Let’s say we’ve obtained Blazor powering a bit of UI for internet and likewise native apps by .NET MAUI. We wish to present details about the identify of system the app is operating—that is very platform-specific throughout internet and cell/desktop.
And we would like the window dimension wherein our app is rendering—additionally very completely different connotations between internet browsers and the .NET MAUI hosted WebView inside a cell/desktop app.

We wish to preserve our code clear with a constant API, however clearly have completely different implementations throughout platforms.

Step one is perhaps to outline an interface in our shared UI library, like so:

Circled under BlazorSharedUI is SharedServices with IPlatformInfo.cs

utilizing System;

namespace BlazorSharedUI.SharedServices
{
    public interface IPlatformInfo
    {
        public string GetPlatformName();
        public Process<string> GetWindowSize();
    }
}

Internet Implementation

Now, allow us to look to implement our interface for Blazor UI operating on the net, AKA in an internet browser. The best strategy to get the window dimensions of a browser is thru JavaScript—so let’s write some in a easy little file dropped in
our challenge.

Circled under BlazorForWeb.Client are Services with BrowserService.cs and PlatformInfo.cs, and WindowDimension.js under wwwroot

window.getDimensions = operate() {
    return {
    width: window.innerWidth,
            peak: window.innerHeight
        };
};

How does our Blazor C# code discuss to JavaScript? Easy—it’s constructed into Blazor runtime as a JavaScript Interop. We are able to invoke JS from .NET and .NET from JS—let’s use our newly outlined JS operate inside BrowserService class,
like so:

utilizing System;
utilizing Microsoft.JSInterop;
utilizing System.Threading.Duties;

namespace BlazorForWeb.Consumer.Providers
{
    public class BrowserService
    {
        non-public readonly IJSRuntime _js;

        public BrowserService(IJSRuntime js)
        {
            _js = js;
        }

        public async Process<BrowserDimension> GetDimensions()
        {
            return await _js.InvokeAsync<BrowserDimension>("getDimensions");
        }

    }

    public class BrowserDimension
    {
        public int Width { get; set; }
        public int Peak { get; set; }
    }
}

Now we are able to get to implementing the Interface for Blazor code operating on internet browsers—the platform identify is given and we are able to retrieve browser window dimension from BrowserService, which in flip invokes our JS operate.

utilizing System;
utilizing BlazorSharedUI.SharedServices;
utilizing System.Threading.Duties;

namespace BlazorForWeb.Consumer.Providers
{
    public class PlatformInfo : IPlatformInfo
    {
        BrowserService myService;

        public PlatformInfo(BrowserService service)
        {
            myService = service;
        }

        public string GetPlatformName()
        {
            return "Browser";
        }

        public async Process<string> GetWindowSize()
        {
            var dimension = await myService.GetDimensions();
            int Peak = dimension.Peak;
            int Width = dimension.Width;
            string WindowDimension = Width + "x" + Peak;

            return WindowDimension;
        }
    }
}

Native Implementation

Now let’s get to the interface implementation for Blazor code operating by .NET MAUI on cell/desktop. Although Blazor UI is being rendered inside a browser-based WebView, it’s inside the shell of a .NET MAUI really native app.

That is the place Blazor and .NET MAUI shine collectively—they’ve the very same .NET runtime. So our Blazor C# code can faucet into .NET MAUI APIs—abstracted for every platform the app runs on. Attending to system identify and native window dimensions
is a bit of cake with .NET MAUI APIs, like so:

Circled under BlazorForNative is Services with PlatformInfo.cs

utilizing System;
utilizing BlazorSharedUI.SharedServices;

namespace BlazorForNative.Providers
{
    public class PlatformInfo : IPlatformInfo
    {
        public string GetPlatformName()
        {
            return DeviceInfo.Present.Platform.ToString();
        }

        public Process<string> GetWindowSize()
        {
            double Width = DeviceDisplay.MainDisplayInfo.Width;
            double Peak = DeviceDisplay.MainDisplayInfo.Peak;

            string WindowSize = Width + "x" + Peak;
            return Process.FromResult(WindowSize);
        }
    }
}

Shared UI

With interface implementations finished for each internet and native apps, it’s time to wire issues up so we leverage the implementations. With platform variations tucked away, we are able to now write generic Blazor markup/C# in our Shared UI challenge that
make use of the constant Interface APIs.

Circled under BlazorSharedUI Pages with Counter.razor and Index.razor, which contains Index.razor.cs

First, let’s add the system identify and window dimensions info to the Index.razor web page—that is shared Blazor UI for internet and .NET MAUI app.

@web page "https://www.telerik.com/" 

<PageTitle>Index</PageTitle>

<h1>Hiya, World!</h1>

Welcome to your new app.

<SurveyPrompt Title="How is Blazor working for you?" />

Blazor operating on Platform: @PlatformInfo?.GetPlatformName()
<br />
<br />
Window Dimensions: @_windowDimensions

As an alternative of writing C# embedded with our HTML markup, we are able to simply have an Index.razor.cs file that holds the remainder of the partial class—conventions are good. Right here we are able to invoke the Interface strategies—the OnAfterRenderAsync() and
StateHasChanged() triggers are used in order that Blazor’s JS Interop is able to invoke our JS operate for internet apps.

utilizing System;
utilizing BlazorSharedUI.SharedServices;
utilizing Microsoft.AspNetCore.Elements;

namespace BlazorSharedUI.Pages
{
    public partial class Index
    {
        [Inject]
        non-public IPlatformInfo? PlatformInfo { get; set; }

        non-public string? _windowDimensions;

        protected override async Process OnAfterRenderAsync(bool firstRender)
        {
            if (firstRender)
            {
                _windowDimensions = await PlatformInfo?.GetWindowSize();
                StateHasChanged();
            }
        }
    }
}

Final however not the least, we have to wire up platform-specific interface implementations by dependency injection—right here’s how within the Blazor internet app’s Program.cs:

utilizing Microsoft.AspNetCore.Elements.Internet;
utilizing Microsoft.AspNetCore.Elements.WebAssembly.Internet hosting;
utilizing BlazorForWeb.Consumer;
utilizing BlazorForWeb.Consumer.Providers;
utilizing BlazorSharedUI.SharedServices;

var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("#app");
builder.RootComponents.Add<HeadOutlet>("head::after");

builder.Providers.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
builder.Providers.AddScoped<IPlatformInfo, PlatformInfo>();
builder.Providers.AddScoped<BrowserService>();

await builder.Construct().RunAsync();

We are able to now run the Blazor internet app domestically and voila—Blazor UI renders as anticipated and we are able to show platform identify and window dimensions.

BlazorEverywhere app with window dimensions 1832x1040

And right here is dependency injection offering the interface implementations being wired up within the .NET MAUI with Blazor app’s Program.cs:

utilizing Microsoft.AspNetCore.Elements.WebView.Maui;
utilizing BlazorForNative.Information;
utilizing BlazorSharedUI.SharedServices;
utilizing BlazorForNative.Providers;

namespace BlazorForNative;

public static class MauiProgram
{
    public static MauiApp CreateMauiApp()
    {
        var builder = MauiApp.CreateBuilder();
        builder
            .UseMauiApp<App>()
            .ConfigureFonts(fonts =>
            {
                fonts.AddFont("OpenSans-Common.ttf", "OpenSansRegular");
            });

        builder.Providers.AddMauiBlazorWebView();
#if DEBUG
        builder.Providers.AddBlazorWebViewDeveloperTools();
#endif

        builder.Providers.AddSingleton<WeatherForecastService>();
        builder.Providers.AddScoped<IPlatformInfo, PlatformInfo>();

        return builder.Construct();
    }
}

We should always now be able to run our .NET MAUI app on any chosen platform—on iOS, Android, Home windows, macOS. It’s enjoyable to see the platform particular system identify and window dimensions replace for varied simulators/gadgets the app runs on—shared
Blazor UI tapping into interface implementations and .NET MAUI APIs throughout platforms.

BlazorEverywhere app with window dimensions 4096x2560

’Tis the Season

It’s that point of the yr—the vacation season is upon us. No matter we rejoice, let’s attempt to be merry and grateful for what we now have. An overzealous you could have purchased lots of wrapping paper for packing presents for family members—reusing
is nice. Whereas presents could look the identical wrapped up, you’ll be making an attempt to cater to the individuals you might be packing the presents for—their tastes matter.

Blazor is understandably probably the most thrilling internet framework for .NET builders—permitting C# to run server-side or fully client-side by WebAssembly. And .NET MAUI ushers within the subsequent technology of native cross-platform growth on .NET,
effortlessly reaching cell/desktop platforms from a single codebase. With a contemporary WebView UI element, .NET MAUI welcomes Blazor to fatherland—internet parts and types might be rendered inside native apps on iOS/Android/Home windows/Mac.

Although Blazor is powering UI/UX throughout internet and native apps, there could also be variations to how issues work throughout platforms. Generic interfaces with platform-specific implementations can enable builders to have constant shared code that occurs
to work in a different way throughout internet and cell/desktop platforms. Sharing throughout variations is caring and retains your codebase on the good checklist.


Strive Telerik UI for Blazor

Develop new Blazor apps and modernize legacy internet tasks in half the time with a high-performing Grid and 100+ really native, easy-to-customize Blazor parts to cowl any requirement. Strive it without cost with our 30-day trial and revel in our industry-leading
assist.

Strive Now

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles