Azure

A Complete Information to Migrating Azure Features C# to C# 12 with .NET 8 Remoted

Overview

Although Azure Features continues to evolve, its underlying know-how additionally does. With the introduction of C# 12 and .NET 8 Remoted Course of, builders face an thrilling alternative to reinforce the efficiency, scalability, and maintainability of their serverless functions. Senior builders and tech leads will discover detailed code examples and insights into migrating Azure Features from older C# variations to C# 12 with .NET 8 within the Remoted Course of mannequin on this article.

Perceive the .NET 8 Remoted Course of Mannequin

 A .NET 8 Remoted Course of mannequin separates the Azure Features runtime from the perform code, which improves efficiency and simplifies dependency administration. Rather than the standard Microsoft.NET.Sdk.Features package deal, this mannequin requires using Microsoft.Azure.Features.Employee and Microsoft.Azure.Features.Employee.Sdk packages.

Key Steps

  • Replace your undertaking file to make use of Microsoft.Azure.Features.Employee as an alternative of Microsoft.NET.Sdk.Features.
  • Regulate your perform app’s entry level to accommodate the brand new runtime mannequin.

Instance Challenge File Migration

<Challenge Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>net8.0</TargetFramework>
    <AzureFunctionsVersion>v4</AzureFunctionsVersion>
    <OutputType>Exe</OutputType>
    <ImplicitUsings>allow</ImplicitUsings>
    <Nullable>allow</Nullable>
  </PropertyGroup>
  <ItemGroup>
    <FrameworkReference Embody="Microsoft.AspNetCore.App" />
    <PackageReference Embody="Microsoft.Azure.Features.Employee" Model="1.20.1" />
    <PackageReference Embody="Microsoft.Azure.Features.Employee.Extensions.Http" Model="3.1.0" />
    <PackageReference Embody="Microsoft.Azure.Features.Employee.Extensions.Http.AspNetCore" Model="1.2.0" />
    <PackageReference Embody="Microsoft.Azure.Features.Employee.Sdk" Model="1.16.4" />
    <PackageReference Embody="Microsoft.ApplicationInsights.WorkerService" Model="2.21.0" />
    <PackageReference Embody="Microsoft.Azure.Features.Employee.ApplicationInsights" Model="1.1.0" />
  </ItemGroup>
  <ItemGroup>
    <ProjectReference Embody="..AzureFunctionsApp.SharedAzureFunctionsApp.Shared.csproj" />
  </ItemGroup>
  <ItemGroup>
    <None Replace="host.json">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
    </None>
    <None Replace="native.settings.json">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
      <CopyToPublishDirectory>By no means</CopyToPublishDirectory>
    </None>
  </ItemGroup>
  <ItemGroup>
    <Utilizing Embody="System.Threading.ExecutionContext" Alias="ExecutionContext" />
  </ItemGroup>
</Challenge>

Improve Code to Leverage C# 12 Options

It is strongly recommended that you just take into account adopting the next options in C# 12 the place they’re relevant, in an effort to simplify code and enhance efficiency:

Constructor parameter dealing with and initialization ought to be simplified for main constructors.

Earlier than C# 12

namespace AzureFunctionsApp.Shared.Fashions
{
    public class Particular person
    {
        public string FirstName { get; }
        public string LastName { get; }
        public string EmailAddress { get; }
        public string TelphoneNumber { get; }


        public Particular person(string firstName, string lastName, string eamilAddress, string telephoneNumber)
        {
            FirstName = firstName;
            LastName = lastName;
            EmailAddress = eamilAddress;
            TelphoneNumber = telephoneNumber;
        }

    }
}

After C# 12

    namespace AzureFunctionsApp.Shared.Fashions
    public readonly file struct Particular person(string FirstName, string LastName, string EmailAddress, string TelephoneNumber);

Document Structs:  Immutable knowledge constructions that present higher efficiency and reminiscence effectivity.

Instance

    public readonly file struct Particular person(string FirstName, string LastName, string EmailAddress, string TelephoneNumber);

Refactor to Asynchronous Programming Mannequin

The Remoted Course of mannequin promotes asynchronous operations to keep away from blocking threads and enhance scalability. Guarantee all I/O-bound operations are asynchronous and make the most of async and await key phrases correctly.

Instance of Earlier than

utilizing AzureFunctionsApp.Shared.Providers.Interfaces;

namespace AzureFunctionsApp.Shared.Providers;


public class DataService
{
    public async Process<string> GetData()
    {

        var knowledge = await SomeLongRunningOperation();


        await DoAnotherAsyncOperation();


        return knowledge;
    }


    public async Process<string> SomeLongRunningOperation()
    {
        await Process.Delay(1000); 
        return "Information from long-running operation";
    }


    public async Process DoAnotherAsyncOperation()
    {
        await Process.Delay(500); 
    }
}

Instance of After

It is very important be certain that all technique calls that assist asynchronous operations are awaited accurately.

IDataService.cs:

namespace AzureFunctionsApp.Shared.Providers.Interfaces;

public interface IDataService
{
    string GetData();
    Process<string> GetDataAsync();

    Process<string> SomeLongRunningOperationAsync();

    Process DoAnotherAsyncOperationAsync();
}

DataService.cs:

utilizing AzureFunctionsApp.Shared.Providers.Interfaces;
namespace AzureFunctionsApp.Shared.Providers;
public class DataService: IDataService
{
    public string GetData()
    {
        return "Good day from Ziggy Rafiq!"; 
    }

    public async Process<string> GetDataAsync()
    {
        
        var knowledge = await SomeLongRunningOperationAsync();

        
        await DoAnotherAsyncOperationAsync();

        
        return knowledge;
    }

    
    public async Process<string> SomeLongRunningOperationAsync()
    {
        await Process.Delay(1000); 
        return "Lengthy-running operation consequence";
    }

    public async Process DoAnotherAsyncOperationAsync()
    {
        await Process.Delay(500);
    }
}

Adapt Dependency Injection and Configuration

For the remoted mannequin, dependency injection (DI) and configuration administration are dealt with otherwise. IServiceCollection is used to configure providers and ConfigurationBuilder is used to configure software settings.

utilizing AzureFunctionsApp.Shared.Providers;
utilizing AzureFunctionsApp.Shared.Providers.Interfaces;
utilizing Microsoft.Azure.Features.Employee;
utilizing Microsoft.Extensions.DependencyInjection;
utilizing Microsoft.Extensions.Internet hosting;

var host = new HostBuilder()
    .ConfigureFunctionsWebApplication()
    .ConfigureServices(providers =>
    {
        providers.AddSingleton<IDataService, DataService>();
        providers.AddApplicationInsightsTelemetryWorkerService();
        providers.ConfigureFunctionsApplicationInsights();
    })
    .Construct();

host. Run();

Configuration Setup

utilizing Microsoft.AspNetCore.Http;
utilizing Microsoft.AspNetCore.Mvc;
utilizing Microsoft.Azure.Features.Employee;
utilizing Microsoft.Extensions.Configuration;
utilizing Microsoft.Extensions.Logging;

namespace AzureFunctionsApp;

public class ZiggyFunction
{
    personal readonly ILogger<ZiggyFunction> _logger;
    personal readonly IConfiguration _configuration;

    public ZiggyFunction(ILogger<ZiggyFunction> logger, IConfiguration configuration)
    {
        _logger = logger;
        _configuration = configuration;
    }

    
    [Function(nameof(ZiggyFunction))]
    public IActionResult Run([HttpTrigger(AuthorizationLevel.Function, "get", "post")] HttpRequest req)
    {
        string? ziggyAppSettingConfiguration = string.IsNullOrWhiteSpace(_configuration["ZiggyAppSetting"]) ? "ZiggyDefaultValue": _configuration["ZiggyAppSetting"];

        _logger.LogInformation("Good day from Ziggy Rafiq");
        return new OkObjectResult("Welcome to Ziggy Azure Features!");
    }
}

Abstract

Azure Features customers can profit from improved efficiency and new language options after they migrate to C# 12 with .NET 8 Remoted Course of. This up to date atmosphere could be successfully transitioned by understanding the brand new mannequin, leveraging trendy C# options, and adapting your code for asynchronous programming and DI. It’s crucial to check and validate your serverless functions to make sure a clean migration. Undertake these practices to reinforce their effectivity and scalability.

You may reap the benefits of the newest developments in Azure Features and .NET by following these greatest practices.

For the whole supply code for the examples on this article, please go to my GitHub repository. I would respect your assist in the event you favored this text and adopted me on LinkedIn.

Know extra about our firm at Skrots. Know extra about our providers at Skrots Providers, Additionally checkout all different blogs at Weblog at Skrots

Show More

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button