Movatterモバイル変換


[0]ホーム

URL:


Strawberry Shakev13

Get started with Strawberry Shake and Xamarin

In this tutorial we will walk you through the basics of adding a Strawberry Shake GraphQL client to a .NET project. For this example we will create a Blazor for WebAssembly application and fetch some simple data from our demo backend.

Strawberry Shake is not limited to Blazor and can be used with any .NET standard compliant library.

In this tutorial, we will teach you:

  • How to add the Strawberry Shake CLI tools.
  • How to generate source code from .graphql files, that contain operations.
  • How to use the generated client in a classical or reactive way.

Step 1: Add the Strawberry Shake CLI tools

The Strawberry Shake tool will help you to set up your project to create a GraphQL client.

Open your preferred terminal and select a directory where you want to add the code of this tutorial.

  1. Create a dotnet tool-manifest.
Bash
dotnet new tool-manifest
  1. Install the Strawberry Shake tools.
Bash
dotnet tool install StrawberryShake.Tools --local

Step 2: Create a Blazor WebAssembly project

Next, we will create our Blazor project so that we have a little playground.

  1. First, a new solution calledDemo.sln.
Bash
dotnet new sln -n Demo
  1. Create a new Blazor for WebAssembly application.
Bash
dotnet new wasm -n Demo
  1. Add the project to the solutionDemo.sln.
Bash
dotnet sln add ./Demo

Step 3: Install the required packages

Strawberry Shake has meta packages, that will help pulling in all necessary dependencies in your project. Choose between either of these:

a. For Blazor add theStrawberryShake.Blazor package to your project.

Bash
dotnet add Demo package StrawberryShake.Blazor

b. For MAUI add theStrawberryShake.Maui package to your project.

Bash
dotnet add Demo package StrawberryShake.Maui

c. For Console apps add theStrawberryShake.Server package to your project.

Bash
dotnet add Demo package StrawberryShake.Server

Step 4: Add a GraphQL client to your project using the CLI tools

To add a client to your project, you need to rundotnet graphql init {{ServerUrl}} -n {{ClientName}}.

In this tutorial we will use our GraphQL workshop to create a list of sessions that we will add to our Blazor application.

If you want to have a look at our GraphQL workshop head overhere.

  1. Add the conference client to your Blazor application.
Bash
dotnet graphql init https://workshop.chillicream.com/graphql/ -n ConferenceClient -p ./Demo
  1. Customize the namespace of the generated client to beDemo.GraphQL. For this head over to the.graphqlrc.json and insert a namespace property to theStrawberryShake section.
JSON
{
"schema": "schema.graphql",
"documents": "**/*.graphql",
"extensions": {
"strawberryShake": {
"name": "ConferenceClient",
"namespace": "Demo.GraphQL",
"url": "https://workshop.chillicream.com/graphql/",
"dependencyInjection": true
}
}
}

Now that everything is in place let us write our first query to ask for a list of session titles of the conference API.

  1. Choose your favorite IDE and the solution. If your are using VSCode do the following:
Bash
code ./Demo
  1. Create new query documentGetSessions.graphql with the following content:
GraphQL
query GetSessions {
sessions(order: { title: ASC }) {
nodes {
title
}
}
}
  1. Compile your project.
Bash
dotnet build

With the project compiled, you should now see in the directory./obj/<configuration>/<target-framework>/berry the generated code that your applications can leverage. For example, if you've run a Debug build for .NET 8, the path would be./obj/Debug/net8.0/berry.

Visual Studio code showing the generated directory.

  1. Head over to theProgram.cs and add the newConferenceClient to the dependency injection.

In some IDEs it is still necessary to reload the project after the code was generated to update the IntelliSense. So, if you have any issues in the next step with IntelliSense just reload the project and everything should be fine.

C#
public class Program
{
public static async Task Main(string[] args)
{
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("#app");
builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
builder.Services
.AddConferenceClient()
.ConfigureHttpClient(client => client.BaseAddress = new Uri("https://workshop.chillicream.com/graphql"));
await builder.Build().RunAsync();
}
}
  1. Go to_Imports.razor and addDemo.GraphQL to the common imports
@using System.Net.Http
@using System.Net.Http.Json
@using Microsoft.AspNetCore.Components.Forms
@using Microsoft.AspNetCore.Components.Routing
@using Microsoft.AspNetCore.Components.Web
@using Microsoft.AspNetCore.Components.Web.Virtualization
@using Microsoft.AspNetCore.Components.WebAssembly.Http
@using Microsoft.JSInterop
@using Demo
@using Demo.Shared // (from .NET 8, `Demo.Layout`)
@using Demo.GraphQL

Step 5: Use the ConferenceClient to perform a simple fetch

In this section we will perform a simple fetch with ourConferenceClient. We will not yet look at state or other things that come with our client but just perform a simple fetch.

  1. Head over toPages/Index.razor (from .NET 8,Home.razor).

  2. Add inject theConferenceClient beneath the@pages directive.

@page "/" @inject ConferenceClient ConferenceClient;
  1. Introduce a code directive at the bottom of the file.
@page "/" @inject ConferenceClient ConferenceClient;
<h1>Hello, world!</h1>
Welcome to your new app.
<SurveyPromptTitle="How is Blazor working for you?"/>
@code { }
  1. Now let's fetch the titles with our client.
@page "/" @inject ConferenceClient ConferenceClient;
<h1>Hello, world!</h1>
Welcome to your new app.
<SurveyPromptTitle="How is Blazor working for you?"/>
@code { private string[] titles = Array.Empty<string
>(); protected override async Task OnInitializedAsync() { // Execute our
GetSessions query var result = await
ConferenceClient.GetSessions.ExecuteAsync(); // aggregate the titles from the
result titles = result.Data.Sessions.Nodes.Select(t => t.Title).ToArray(); //
signal the components that the state has changed. StateHasChanged(); }
}</string
>
  1. Last, let's render the titles on our page as a list.
@page "/" @inject ConferenceClient ConferenceClient;
<h1>Hello, world!</h1>
Welcome to your new app.
<SurveyPromptTitle="How is Blazor working for you?"/>
<ul>
@foreach (string title in titles) {
<li>@title</li>
}
</ul>
@code { private string[] titles = Array.Empty<string
>(); protected override async Task OnInitializedAsync() { // Execute our
GetSessions query var result = await
ConferenceClient.GetSessions.ExecuteAsync(); // aggregate the titles from the
result titles = result.Data.Sessions.Nodes.Select(t => t.Title).ToArray(); //
signal the components that the state has changed. StateHasChanged(); }
}</string
>
  1. Start the Blazor application withdotnet run --project ./Demo and see if your code works.

Started Blazor application in Microsoft Edge

Step 6: Using the built-in store with reactive APIs

The simple fetch of our data works. But every time we visit the index page it will fetch the data again although the data does not change often. Strawberry Shake also comes with state management where you can control the entity store and update it when you need to. In order to best interact with the store we will useSystem.Reactive from Microsoft. Let's get started :)

  1. Install the packageSystem.Reactive.
Bash
dotnet add Demo package System.Reactive
  1. Next, let us update the_Imports.razor with some more imports, namelySystem,System.Reactive.Linq,System.Linq andStrawberryShake.
C#
@using System
@using System.Reactive.Linq
@using System.Linq
@using System.Net.Http
@using System.Net.Http.Json
@using Microsoft.AspNetCore.Components.Forms
@using Microsoft.AspNetCore.Components.Routing
@using Microsoft.AspNetCore.Components.Web
@using Microsoft.AspNetCore.Components.Web.Virtualization
@using Microsoft.AspNetCore.Components.WebAssembly.Http
@using Microsoft.JSInterop
@using Demo
@using Demo.Shared // (from .NET 8, `Demo.Layout`)
@using Demo.GraphQL
@using StrawberryShake
  1. Head back toPages/Index.razor (from .NET 8,Home.razor) and replace the code section with the following code:
C#
private string[] titles = Array.Empty<string>();
private IDisposable storeSession;
protected override void OnInitialized()
{
storeSession =
ConferenceClient
.GetSessions
.Watch(StrawberryShake.ExecutionStrategy.CacheFirst)
.Where(t => !t.Errors.Any())
.Select(t => t.Data.Sessions.Nodes.Select(t => t.Title).ToArray())
.Subscribe(result =>
{
titles = result;
StateHasChanged();
});
}

Instead of fetching the data we watch the data for our request. Every time entities of our results are updated in the entity store our subscribe method will be triggered.

Also we specified on our watch method that we want to first look at the store and only of there is nothing in the store we want to fetch the data from the network.

Last, note that we are storing a disposable on our component state calledstoreSession. This represents our session with the store. We need to dispose the session when we no longer display our component.

  1. ImplementIDisposable and handle thestoreSession dispose.
C#
@page "/"
@inject ConferenceClient ConferenceClient;
@implements IDisposable
<h1>Hello, world!</h1>
Welcome to your new app.
<SurveyPrompt Title="How is Blazor working for you?" />
<ul>
@foreach (var title in titles)
{
<li>@title</li>
}
</ul>
@code {
private string[] titles = Array.Empty<string>();
private IDisposable storeSession;
protected override void OnInitialized()
{
storeSession =
ConferenceClient
.GetSessions
.Watch(StrawberryShake.ExecutionStrategy.CacheFirst)
.Where(t => !t.Errors.Any())
.Select(t => t.Data.Sessions.Nodes.Select(t => t.Title).ToArray())
.Subscribe(result =>
{
titles = result;
StateHasChanged();
});
}
public void Dispose()
{
storeSession?.Dispose();
}
}

Every time we move away from our index page Blazor will dispose our page which consequently will dispose our store session.

  1. Start the Blazor application withdotnet run --project ./Demo and see if your code works.

Started Blazor application in Microsoft Edge

The page will look unchanged.

  1. Next, open the developer tools of your browser and switch to the developer tools console. Refresh the site so that we get a fresh output.

Microsoft Edge developer tools show just one network interaction.

  1. Switch between theIndex and theCounter page (back and forth) and watch the console output.

The Blazor application just fetched a single time from the network and now only gets the data from the store.

Step 7: Using GraphQL mutations

In this step we will introduce a mutation that will allow us to rename a session. For this we need to change our Blazor page a bit.

  1. We need to get the session id for our session so that we can call therenameSession mutation. For this we will rewrite ourGetSessions operation.
GraphQL
query GetSessions {
sessions(order: { title: ASC }) {
nodes {
...SessionInfo
}
}
}
fragment SessionInfo on Session {
id
title
}
  1. Next we need to restructure theIndex.razor (from .NET 8,Home.razor) page.
Last updated on2025-06-16 byGlen
About this article
Help us improving our content
  1. Edit on GitHub
  2. Discuss on Slack

[8]ページ先頭

©2009-2025 Movatter.jp