Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Getting Started with Blazor: Application Bootstrap and Life Cycle Methods

0.00/5 (No votes)
16 Jul 2018 2  
How to get started with Blazor: Application Bootstrap and life cycle methods

Introduction

We know how web assembly and C# can be a game changer and will help the C# to run on Browser so moving to the next article, let’s see how we can setup Blazor in your machine and how we can get started with our first application with Blazor.

Agenda

  1. Environment setup
  2. Application Bootstrap Process
  3. Application Life Cycle Methods
  4. Conclusion

1. Environment Setup

While writing this article, the new experimental blazor framework 0.0.4 is been announced by Microsoft. To get this version, there are few prerequisites as below:

  1. Install .NET Core SDK 2.1 from here
  2. Install VS 2017 Preview (15.7) with Web Work Bench selected while installation
  3. Most important step is to install the language service extension for blazor from here

To verify the installation, open Visual Studio and let's create one ASP.NET Core web application. We will be able to see the following templates:

App setup

2. Getting Started and Building First Blazor App

We have done the setup part. Now, it’s time to create our first demo app with Blazor. How we can do this? Follow the below steps:

  1. Create a new Project with the ASP.NET Core web Application selected Name it as BlazorDemoApp1 and Click Ok.

    Project setup

  2. Next step is to select the Environment using proper Template for the same.
    1. We need to make sure .NET Core is selected. ASP.NET Core 2.0 or 2.1 as well is selected for the same.
    2. Next step is to select the template for the Blazor application for our demo, we will select the Template called Blazor and press Ok.

3. Application Bootstrap

Where does our application bootstrap? Obviously, it is the main method in the Program.cs. How does it look? Let's look at the code snippet below:

Using the Code

public class Program
    {
        static void Main(string[] args)
        {
            var serviceProvider = new BrowserServiceProvider(services =>
            {
                // Add any custom services here
            });
 
            new BrowserRenderer(serviceProvider).AddComponent<App>("app");
        }
    }

This is the place where we decide which component will be loaded in this, the DOM element selector argument will decide whether we want to load the Root Component or not in our case, the app element in the index.html will be used for the rendering.

Main method can be used to add the various services which will be used for the DI in the later part of the app.

When we see the index.html snippet which is as follows:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width">
    <title>WebApplication2</title>
    <base href="/" />
    <link href="css/bootstrap/bootstrap.min.css" rel="stylesheet" />
    <link href="css/site.css" rel="stylesheet" />
</head>
<body>
    <app>Loading...</app> <!--Root Component Loads here-->
 
    <script type="blazor-boot"></script>
</body>
</html>

Here, the Blazor-boot is used as the script type now question is why it is used here in the index.html.

So when we build the application at that time, the blazor-boot is replaced with the bootstrapping script which handles the .NET Run time and executes entry point of the application. The following screenshot can tell us what is loaded at the place of the blazor-boot.

Here, we can see all the things needed to run the .NET runtime are loaded with this and our app gets bootstrapped.

App Life Cycle

1. Application Life Cycle Methods

All right, we have set up our project. Let's dig out the details of the Application life cycle method of the Blazor App. There are around 7 life cycle methods available in the Blazor app Blazor provides the Synchronous as well the asynchronous life cycle methods. Let's see one by one how they can be differentiated.

There are mainly 7 life cycle methods. Let's see all of them one by one.

1. OnInit ()

This is the synchronous version of the application method which gets executed when the component gets Initialized, this gets executed when the component is completely loaded, we can use this method to load data from services as after this method, each control in the UI is loaded. This is executed when the component is ready and when it has received the values from the parent in render tree.

2. OnInitAsync ()

This is the asynchronous version of the application method which gets executed when the component is initialized, this is called when the component is completely initialized. This can be used to call the data service or to load the data from the service. This is executed when the component is ready and when it has received the values from the parent in render tree.

3. OnParametersSet ()

This is the synchronous way of setting the parameter when the component receives the parameter from its parent component, this is called when the Initialization of the component occurs.

4. OnParametersSetAsync ()

This is the Asynchronous way of setting the parameter when the component received the parameter from the parent component, this gets called when the initialization of the component occurs.

5. ShouldRender ()

We use this method to suppress the refreshing of the UI if this method returns true then UI is refreshed, otherwise changes are not sent to UI, one thing about ShouldRender() is it always does the initial rendering despite its return value.

6. OnAfterRender ()

This is called each time when the component is done with the rendering all the references to the component are populated now, we can make use of this method to perform the additional steps like initializing the other components and all.

7. OnAfterRenderAsync ()

This method is the asynchronous version of the OnAfrerRender() which gets called when the rendering of all the references to the component are populated we can use this method to do additional initializing of the third party component.

The complete code demonstrating the Application life cycle is as follows:

@page "/"
 <h1>Application Life cycle Methods ..</h1>
@foreach (var item in EventType){  @item <hr />}
 @functions{
   List<string> EventType = new List<string>();
        protected override void OnInit()
        {
            EventType.Add(" 1 OnInit");
        }
        protected override async Task OnInitAsync()
        { 
            EventType.Add("2 OnInit Async");
            await Task.Delay(1000);          
        }
 
        protected override void OnParametersSet()
        {
            EventType.Add("3 On Parameter set ");
        }
        protected override async Task OnParametersSetAsync()
        {
            EventType.Add(" 4 OnParametersSet Async Started");
            await Task.Delay(1000);         
        }
 
        protected override bool ShouldRender()
        {
            EventType.Add(" 5 Should render called");
            return true;
        }
        protected override void OnAfterRender()
        {
            EventType.Add(" 6 OnAfterRenderStarted");
        }
 
        protected override  async Task OnAfterRenderAsync()
        {
            EventType.Add(" 7 OnAfterRender Async Started");
            await Task.Delay(1000);           
        }
    }

Running the above code, we will get the output like below:

Application Output

We can see the steps and the way it is been called one by one and the sequence of the application methods.

Conclusion

Blazor is the technology which uses the web assembly for running the application. It uses ASP.NET Core to build the application. It has many similarities with the current UI Framework languages like React or Angular and being a C# developer, it will be a great platform to build the application especially single page application. Although not available for the production system but certainly exciting time is ahead with this. 😊

References

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here