{"id":324,"date":"2023-11-07T20:24:21","date_gmt":"2023-11-07T19:24:21","guid":{"rendered":"https:\/\/archicode.be\/?p=324"},"modified":"2023-11-07T20:53:57","modified_gmt":"2023-11-07T19:53:57","slug":"how-to-use-feature-flags-in-blazor","status":"publish","type":"post","link":"https:\/\/archicode.be\/index.php\/2023\/11\/07\/how-to-use-feature-flags-in-blazor\/","title":{"rendered":"How to use Feature Flags in Blazor"},"content":{"rendered":"\n<p>Feature flags are a way of controlling the availability and behavior of features in your application without changing the code. They can help you with testing, experimentation, and gradual rollout of new functionality. Blazor is a framework for building interactive web UIs using C# and .NET. In this blog post, I will show you how to use feature flags in a Blazor application using a simple in-memory feature manager and a custom feature flag component.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Prerequisites<\/h2>\n\n\n\n<p>To follow this tutorial, you will need:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>A Blazor Server or WebAssembly project. You can use the default template or create your own.<\/li>\n\n\n\n<li>The Microsoft.Extensions.Configuration and Microsoft.Extensions.Configuration.Json NuGet packages. You can install them by using the Package Manager Console or the Manage NuGet Packages option in Visual Studio.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Step 1: Define feature flags in appsettings.json<\/h2>\n\n\n\n<p>The first step is to define some feature flags in appsettings.json. This is a JSON file that stores the configuration settings for your application. You can use it to store the names and values of your feature flags. To do this, follow these steps:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>In the Solution Explorer, right-click on the folder wwwroot and select Add > New Item.<\/li>\n\n\n\n<li>In the Add New Item window, select JSON File and name it appsettings.json. Click Add.<\/li>\n\n\n\n<li>In the appsettings.json file, add a new section called &#8220;FeatureManagement&#8221; and define your feature flags as key-value pairs. For example, you can define a feature flag called &#8220;Counter&#8221;<\/li>\n<\/ul>\n\n\n\n<p>Your appsettings.json file should look something like this:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>{\n  \"FeatureManagement\": {\n    \"Counter\": \"true\"\n  }\n}<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Step 2: Create a feature manager service<\/h2>\n\n\n\n<p>The next step is to create a feature manager service that will read the feature flag settings from appsettings.json and provide a method to check the feature flag state. To do this, follow these steps:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>In the Solution Explorer, right-click on your project and select Add &gt; Class.<\/li>\n\n\n\n<li>Name the class FeatureManager.cs and replace the existing code with the following code:<\/li>\n<\/ul>\n\n\n\n<pre class=\"wp-block-code\"><code>using Microsoft.Extensions.Configuration;\r\nusing System.Threading.Tasks;\r\n\r\nnamespace FeatureFlagBlazorExample.Client.Helpers\r\n{\r\n\r\n    public interface IFeatureManager\r\n    {\r\n        bool IsEnabled(string feature);\r\n    }\r\n\r\n    public class FeatureManager : IFeatureManager\r\n    {\r\n        private readonly IConfiguration _configuration;\r\n\r\n        public FeatureManager(IConfiguration configuration)\r\n        {\r\n            _configuration = configuration;\r\n        }\r\n\r\n        public bool IsEnabled(string feature)\r\n        {\r\n            if (!string.IsNullOrEmpty(feature))\r\n            {\r\n                return  _configuration.GetValue&lt;bool>($\"FeatureManagement:{feature}\");\r\n            }\r\n            return false;\r\n        }\r\n    }\r\n}\r\n<\/code><\/pre>\n\n\n\n<p>This class implements the IFeatureManager interface, which defines a method called IsEnabledAsync that takes a feature name as a parameter and returns a boolean value indicating whether the feature is enabled or not. The class uses the IConfiguration service to access the appsettings.json file and read the feature flag settings.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>In the program.cs file, add the following line before the line that contains await builder.Build().RunAsync();<\/li>\n<\/ul>\n\n\n\n<pre class=\"wp-block-code\"><code>builder.Services.AddSingleton&lt;IFeatureManager, FeatureManager>();<\/code><\/pre>\n\n\n\n<p>This will register the FeatureManager class as a singleton service that implements the IFeatureManager interface.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Step 3: Create a feature flag component<\/h2>\n\n\n\n<p>The final step is to create a feature flag component that will render its child content only if the feature flag with the given name is enabled. It will use the IFeatureManager service to check the feature flag state asynchronously. To do this, follow these steps:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>In the Solution Explorer, right-click on the Pages folder and select Add &gt; Razor Component.<\/li>\n\n\n\n<li>Name the component FeatureFlag.razor and replace the existing code with the following code:<\/li>\n<\/ul>\n\n\n\n<pre class=\"wp-block-code\"><code>@using FeatureFlagBlazorExample.Client.Helpers;\r\n@inject IFeatureManager FeatureManager\r\n\r\n\r\n@if (featureIsEnabled)\r\n{\r\n    @ChildContent\r\n}\r\n\r\n@code {\r\n    private bool featureIsEnabled = false;\r\n\r\n    &#91;Parameter]\r\n    public RenderFragment ChildContent { get; set; }\r\n\r\n    &#91;Parameter]\r\n    public string FlagName { get; set; }\r\n\r\n    protected override void OnInitialized()\r\n    {\r\n        Console.WriteLine(FlagName);\r\n        if (string.IsNullOrEmpty(FlagName))\r\n            return;\r\n\r\n        featureIsEnabled = FeatureManager.IsEnabled(FlagName);\r\n        Console.WriteLine(featureIsEnabled);\r\n    }\r\n\r\n}<\/code><\/pre>\n\n\n\n<p>This component will render its child content only if the feature flag with the given name is enabled. It uses the IFeatureManager service to check the feature flag state asynchronously.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Step 4: Use feature flags in your Blazor components<\/h2>\n\n\n\n<p>Now you are ready to use feature flags in your Blazor components. This will allow you to show or hide features based on the feature flag settings in appsettings.json. To do this, follow these steps:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>In the Solution Explorer, open the Counter.razor component and wrap the content of the page within the FeatureFlag like so <\/li>\n<\/ul>\n\n\n\n<pre class=\"wp-block-code\"><code>@page \"\/counter\"\r\n&lt;FeatureFlag FlagName=\"Counter\">\r\n    &lt;PageTitle>Counter&lt;\/PageTitle>\r\n\r\n    &lt;h1>Counter&lt;\/h1>\r\n\r\n    &lt;p role=\"status\">Current count: @currentCount&lt;\/p>\r\n\r\n    &lt;button class=\"btn btn-primary\" @onclick=\"IncrementCount\">Click me&lt;\/button>\r\n&lt;\/FeatureFlag>\r\n\r\n@code {\r\n    private int currentCount = 0;\r\n\r\n    private void IncrementCount()\r\n    {\r\n        currentCount++;\r\n    }\r\n}\r\n<\/code><\/pre>\n\n\n\n<p>Run your Blazor application and navigate to the home page and the fetch data page. You should see the features appear or disappear based on the feature flag settings in appsettings.json. You can also change the feature flag settings in appsettings.json and refresh the app in the browser.  If it doesn&#8217;t work, you might need to check whether you have hot reload enabled or check if you actualy saved the change in the appsettings.json.<\/p>\n\n\n\n<p>You can find the code here <a href=\"https:\/\/github.com\/HerraHak\/FeatureFlagBlazorExample\/\" target=\"_blank\" rel=\"noreferrer noopener\">HerraHak\/FeatureFlagBlazorExample (github.com)<\/a><\/p>\n\n\n\n<p><em>Happy Coding !<\/em><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Feature flags are a way of controlling the availability and behavior of features in your application without changing the code. They can help you with testing, experimentation, and gradual rollout of new functionality. Blazor is a framework for building interactive web UIs using C# and .NET. In this blog post, I will show you how&#8230;<\/p>\n","protected":false},"author":1,"featured_media":335,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_newsletter_tier_id":0,"footnotes":"","jetpack_publicize_message":"","jetpack_is_tweetstorm":false,"jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":true,"jetpack_social_options":{"image_generator_settings":{"template":"highway","enabled":false}}},"categories":[1],"tags":[],"class_list":["post-324","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-uncategorized"],"jetpack_publicize_connections":[],"jetpack_sharing_enabled":true,"jetpack_featured_media_url":"https:\/\/archicode.be\/wp-content\/uploads\/2023\/11\/4b6f8d86-a588-4313-8cc9-4c41a90aaae5.jpeg","jetpack-related-posts":[{"id":92,"url":"https:\/\/archicode.be\/index.php\/2019\/06\/10\/how-to-blazorify-an-existing-mvc-app\/","url_meta":{"origin":324,"position":0},"title":"How to blazorify an existing mvc app","author":"Hakim","date":"June 10, 2019","format":false,"excerpt":"Blazor is awesome. \u00a0If you don't know what it is, you can check it out here\u00a0but to summarize, it's a framework that allows .net code to run in your browser using the power of Web Assembly. I've found a lot of tutorials using the official blazor templates but only hints\u2026","rel":"","context":"In &quot;.NET&quot;","block_context":{"text":".NET","link":"https:\/\/archicode.be\/index.php\/category\/net\/"},"img":{"alt_text":"migrate_solution_to_dotnet_core_3.gif","src":"\/wp-content\/uploads\/2019\/06\/migrate_solution_to_dotnet_core_3.gif","width":350,"height":200,"srcset":"\/wp-content\/uploads\/2019\/06\/migrate_solution_to_dotnet_core_3.gif 1x, \/wp-content\/uploads\/2019\/06\/migrate_solution_to_dotnet_core_3.gif 1.5x, \/wp-content\/uploads\/2019\/06\/migrate_solution_to_dotnet_core_3.gif 2x, \/wp-content\/uploads\/2019\/06\/migrate_solution_to_dotnet_core_3.gif 3x, \/wp-content\/uploads\/2019\/06\/migrate_solution_to_dotnet_core_3.gif 4x"},"classes":[]},{"id":162,"url":"https:\/\/archicode.be\/index.php\/2020\/06\/30\/blazor-server-side-or-web-assembly\/","url_meta":{"origin":324,"position":1},"title":"Blazor : server-side or Web assembly","author":"Hakim","date":"June 30, 2020","format":false,"excerpt":"Blazor is amazing. But if you are wondering which of Web Assembly of Server-Side would suit your project, here's an attempt to explain and help","rel":"","context":"In &quot;.NET&quot;","block_context":{"text":".NET","link":"https:\/\/archicode.be\/index.php\/category\/net\/"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":368,"url":"https:\/\/archicode.be\/index.php\/2024\/05\/12\/error-netsdk1082-in-maui-blazor-hybrid-app\/","url_meta":{"origin":324,"position":2},"title":"Error NETSDK1082 in Maui Blazor Hybrid App","author":"Hakim","date":"May 12, 2024","format":false,"excerpt":"There was no runtime pack for Microsoft.AspNetCore.App available for the specified RuntimeIdentifier 'android-x64' If you ever encountered this error in your Maui Blazor hybrid App, this is probably due to authentication.It took me a while to find it out (more than I care to admit) mainly because I had serial\u2026","rel":"","context":"In &quot;.NET&quot;","block_context":{"text":".NET","link":"https:\/\/archicode.be\/index.php\/category\/net\/"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":366,"url":"https:\/\/archicode.be\/index.php\/2024\/05\/11\/understanding-inject-in-blazor-components\/","url_meta":{"origin":324,"position":3},"title":"Understanding @inject in Blazor Components","author":"Hakim","date":"May 11, 2024","format":false,"excerpt":"Blazor, Microsoft\u2019s framework for building interactive client-side web UI with .NET, offers a robust solution for dependency injection (DI) in the form of the\u00a0@inject\u00a0directive. This powerful feature allows developers to inject services directly into their components, promoting a clean and modular architecture. What is Dependency Injection? Dependency Injection (DI) is\u2026","rel":"","context":"In &quot;.NET&quot;","block_context":{"text":".NET","link":"https:\/\/archicode.be\/index.php\/category\/net\/"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":163,"url":"https:\/\/archicode.be\/index.php\/2020\/07\/07\/blazor-convince-your-architect\/","url_meta":{"origin":324,"position":4},"title":"Blazor : convince your CTO (or whomever takes the technical decisions)","author":"Hakim","date":"July 7, 2020","format":false,"excerpt":"When there is something new on the market, we developers want to work with it. There might be several reasons for that, but not always the shortcut decision makers think we favour, which is wanting to try the new shiny thing. Most of the time, we want to work with\u2026","rel":"","context":"In &quot;.NET&quot;","block_context":{"text":".NET","link":"https:\/\/archicode.be\/index.php\/category\/net\/"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":356,"url":"https:\/\/archicode.be\/index.php\/2024\/05\/09\/weird-issues-with-maui-blazor-hybrid-app\/","url_meta":{"origin":324,"position":5},"title":"Weird issues with Maui Blazor Hybrid app","author":"Hakim","date":"May 9, 2024","format":false,"excerpt":"Configuration Visual Studio 2022 17.8 .NET 8.0 Android SDK Steps Create a new \"Maui Blazor Hybrid Solution\" Try building the solution When you try building a Maui Blazor Hybrid Solution, in .NET 8, you might encounter a peculiar issue : Cannot deploy the solution, please select deploy in the Configuration\u2026","rel":"","context":"Similar post","block_context":{"text":"Similar post","link":""},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]}],"_links":{"self":[{"href":"https:\/\/archicode.be\/index.php\/wp-json\/wp\/v2\/posts\/324","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/archicode.be\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/archicode.be\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/archicode.be\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/archicode.be\/index.php\/wp-json\/wp\/v2\/comments?post=324"}],"version-history":[{"count":13,"href":"https:\/\/archicode.be\/index.php\/wp-json\/wp\/v2\/posts\/324\/revisions"}],"predecessor-version":[{"id":338,"href":"https:\/\/archicode.be\/index.php\/wp-json\/wp\/v2\/posts\/324\/revisions\/338"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/archicode.be\/index.php\/wp-json\/wp\/v2\/media\/335"}],"wp:attachment":[{"href":"https:\/\/archicode.be\/index.php\/wp-json\/wp\/v2\/media?parent=324"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/archicode.be\/index.php\/wp-json\/wp\/v2\/categories?post=324"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/archicode.be\/index.php\/wp-json\/wp\/v2\/tags?post=324"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}