Location>code7788 >text

How Blazor Web Apps Implement Auto Mode

Popularity:407 ℃/2024-08-03 16:40:07

This article introduces the Blazor Web application Auto interactive presentation mode of the implementation of the solution, the following example is based on the Known framework to achieve the solution has a total of three projects, the specific implementation steps are as follows:

1. Front-end and back-end shared projects

  • Creating front-end and back-end shared class library projectsSample, defining the system's entity classes, data models, service interfaces, constants, enumerations, etc., the project engineering files are as follows:
<Project Sdk="">
    <PropertyGroup>
        <TargetFramework>net8.0</TargetFramework>
        <ImplicitUsings>enable</ImplicitUsings>
    </PropertyGroup>
</Project>
  • Add the sample service interface to this project, inheriting the frameworkIService
//IService is the Api service interface defined by the framework, which is used to identify the interface as the front-end and back-end interaction interface.
//When the program starts, the framework automatically finds the interface in Assembly and defines the WebApi route according to the interface.
//The example route is:/Test/GetMessage
public interface ITestService : IService {
    Task<string> GetMessageAsync();;
}

2. Client projects

  • Creating a client projectCitationWebAssemblyRequired dependencies, referencesCastleDependent on the dynamic proxy Http request backend WebApi, the project project file content is as follows:
<Project Sdk="">
    <PropertyGroup>
        <TargetFramework>net8.0</TargetFramework>
        <ImplicitUsings>enable</ImplicitUsings>
        <NoDefaultLaunchSettingsFile>true</NoDefaultLaunchSettingsFile>
        <StaticWebAssetProjectMode>Default</StaticWebAssetProjectMode>
    </PropertyGroup>
    <ItemGroup>
        <PackageReference Include="" Version="8.0.6" />
        <PackageReference Include="" Version="8.0.6" />
        <PackageReference Include="" Version="8.0.0" />
        <PackageReference Include="" Version="5.1.1" />
        <PackageReference Include="" Version="2.1.0" />
        <ProjectReference Include="..\Sample\" />
    </ItemGroup>
</Project>
  • Adding Interceptorsclass file that inherits theThe Http Dynamic Proxy is a dynamic proxy that implements the Http dynamic proxy.
using ;

namespace ;

// HttpInterceptorInterceptors wrapped for frameworks
public class HttpClientInterceptor<T>(IServiceScopeFactory provider) : HttpInterceptor<T>(provider), IAsyncInterceptor where T : class {
    protected override async Task<HttpClient> CreateClientAsync() {
        var type = typeof(T);
        var factory = await <IHttpClientFactory>();
        var client = ();
         = new Uri();
        return client;
    }

    public void InterceptAsynchronous(IInvocation invocation) {
         = SendAsync(, );
    }

    public void InterceptAsynchronous<TResult>(IInvocation invocation) {
         = SendAsync<TResult>(, );
    }

    public void InterceptSynchronous(IInvocation invocation) { }
}
  • existAdd the client configuration to the file
//utilizationCastleAgent Generator CreationHttpAgent Type
private static readonly ProxyGenerator Generator = new();

();
//increaseKnownClient,Injecting Interceptor Providers
(info =>
{
     = type => typeof(HttpClientInterceptor<>).MakeGenericType(type);
     = (type, interceptor) =>
    {
        return (type, ((IAsyncInterceptor)interceptor).ToInterceptor());
    };
});
  • Adding Test Page Components
@page "/test"

<h1>@message</h1>

@code {
    //Injecting a service is no different than Server mode injection
    [Inject] private ITestService Service { get; set; }
    private string message.

    protected override async Task OnAfterRenderAsync(bool firstRender) {
        await (firstRender); if (firstRender)
        if (firstRender)
            message = await ();
        //Here's the Service instance that automatically switches depending on the rendering mode
        //When SSR, it's an instance of the class that implements the ITestService on the backend.
        //CSR is the instance of the proxy class created by the Castle proxy generator.
    }
}

3. Server-side projects

  • Creating a server-side project, the project engineering documents are listed below:
<Project Sdk="">
    <PropertyGroup>
        <TargetFramework>net8.0</TargetFramework>
        <ImplicitUsings>enable</ImplicitUsings>
    </PropertyGroup>
    <ItemGroup>
        <PackageReference Include="" Version="8.0.6" />
        <ProjectReference Include="..\\" />
    </ItemGroup>
</Project>
  • modificationsPresentation mode in the document
<Routes @rendermode="InteractiveMode" />

@code {
    private InteractiveAutoRenderMode InteractiveMode => new(false);
}
  • increaseImplementing Service Interfaces
class  TestService : ITestService {
    public Task<string> GetMessageAsync() => ("test");
}
  • existAdd server-side configuration to the file
// Add the Known Framework backend Core
().
//Add the Known Framework auto-generated WebApi
().
//Inject service interfaces
<ITestService, TestService>();

//Use Known Framework static files and WebApi
();

4. Concluding remarks

In this article, the sample code is only for Auto mode implementation scheme for reference, the specific function of the realization, you can see the Known framework examples of source code.