Getting Started with GraphQL in .NET 8
A practical, end‑to‑end primer using Hot Chocolate & Strawberry Shake
Why GraphQL?
If you’ve built—or consumed—REST APIs you’ve felt the pain of under‑ and over‑fetching:
* Needing three endpoints to hydrate one screen
* Getting twenty properties when you only need two
GraphQL fixes that with a single, flexible endpoint where the client asks for exactly what it needs and nothing more. It also supports real‑time subscriptions (think dashboards, chat, IoT feeds) without bolting on a separate signal‑plane.
The .NET ecosystem
-
Hot Chocolate – the premier GraphQL server for ASP.NET Core, now on v14 ChiliCream
-
Strawberry Shake – a type‑safe, code‑gen GraphQL client for any .NET platform ChiliCream
They’re both from the same maintainers (ChilliCream) and play together perfectly.
1 Server Setup with Hot Chocolate
Target: .NET 8 Minimal‑API web app
-
Add packages
-
Program.cs
What those calls do
| Call | Purpose (one‑liner) |
|---|---|
AddGraphQLServer() | Registers the GraphQL middleware, execution engine, schema services, and Banana Cake Pop IDE. |
AddQueryType<T>() / AddMutationType<T>() / AddSubscriptionType<T>() | Maps your C# classes to the root Query, Mutation, and Subscription types in the schema. |
AddInMemorySubscriptions() | Adds an in‑memory pub/sub broker so your mutations can raise events the subscriptions will receive. Ideal for development; swap for Redis, Kafka, etc. in production. |
-
Domain & resolver classes
Run the project and browse to /graphql. Banana Cake Pop appears with schema introspection and an interactive playground.
Open a second tab:
Add a book in tab 1 → the event streams into tab 2. ✨
2 Consuming the API from a .NET Client
Option A – Quick & Dirty HttpClient
Great for scripts/tests:
(No strong typing, no IDE help.)
Option B – Strawberry Shake (type‑safe)
-
Install tooling (once per machine)
-
Create client project
-
Init & generate
The tool:
-
Downloads the schema
-
Generates C# models & operations
-
Adds
IBooksClientto DI
-
Use it
You now have compile‑time safety, auto‑completed queries, and integrated WebSocket subscriptions.
3 Where to Go Next
-
Pagination & filtering – Hot Chocolate supports Relay‑style cursors, projections, and filtering middleware.
-
Authorization – Decorate resolver methods with
[Authorize]or integrate ASP.NET Core policies. -
Production subscriptions – Swap
AddInMemorySubscriptions()for Redis or Kafka back‑planes. -
Monitoring – Hot Chocolate exposes events for OpenTelemetry tracing and metrics ChiliCream.
## Bonus: Subscriptions in Depth — Real‑Time GraphQL for your .NET apps
(drop this straight into the post after the “Where to Go Next” section)
### Why you care 🔔
-
Live dashboards & tickers – push deltas instead of polling REST.
-
Chat, collaboration, IoT – duplex or server‑push communication over one endpoint.
-
Cleaner backend code – one mutation can publish an event that any number of clients subscribe to.
### 1 Transports: WebSocket vs SSE
| Transport | Direction | Specs Hot Chocolate Supports | Notes |
|---|---|---|---|
| WebSockets | full‑duplex | graphql‑ws (recommended) and legacy subscriptions‑transport‑ws ChiliCream | Works everywhere, but needs 80/443 → WS upgrade. |
| SSE (GraphQL‑SSE) | server→client | application/stream+json via the GraphQL‑SSE protocol (v13+) ChiliCream | Firewalls love it; great for dashboards where clients don’t need to talk back. |
In ASP.NET Core you get WebSockets by default (
app.UseWebSockets()), and Hot Chocolate wires up SSE automatically if the client requests it.
### 2 Choosing a Pub/Sub Provider
| Provider | When to use | NuGet & DI |
|---|---|---|
| In‑Memory (default) | Local dev / single node | HotChocolate.Subscriptions → .AddInMemorySubscriptions() |
| Redis | Multi‑node, cheap & battle‑tested | HotChocolate.Subscriptions.Redis → .AddRedisSubscriptions(o ⇒ ConnectionMultiplexer.Connect("redis:6379")) ChiliCream |
| Kafka / Azure SB / Rabbit | Massive fan‑out or enterprise infra | Community packages or write ITopicEventSender / ITopicEventReceiver adapters |
### 3 Securing Subscriptions
-
Handshake auth – add a JWT or bearer token in the initial
connection_initpayload or WebSocket/SSE headers. -
Per‑field rules – decorate resolver methods with
[Authorize]just like queries/mutations. -
Lifecycle hooks – implement
ISocketSessionInterceptorto vet each connect / init / subscribe request (e.g., reject if token expired) ChiliCream.
### 4 Banana Cake Pop quick test
Tab 1 instantly receives the payload—no refresh required.
### 5 Strongly‑Typed Client Subscriptions with Strawberry Shake
Works for console, MAUI, WPF, Blazor, Unity…anything .NET Standard.
tool & package prerequisites (if you haven’t already):
#### a. Tell the code‑gen to use WebSockets
Create or extend .graphqlrc.json in your client project:
#### b. Define the operation
#### c. Generate + wire up
Tip: To multiplex queries + subscriptions over the same socket, set
WebSocketClientOptions.ConnectionInitializerto send your auth token during connect.
### 6 Production Checklist ✅
| Area | Gotcha | Fix |
|---|---|---|
| Load‑balancing | Sticky sessions required for WS | Use Redis/Kafka back‑plane or SSE (stateless). |
| Firewalls / proxies | WS blocked | Fall back to SSE (Accept: text/event-stream). |
| Reconnections | Mobile devices sleep | Enable Strawberry Shake’s retry/reconnect policies. |
| Tracing & metrics | Streams can be chatty | Turn on Hot Chocolate OpenTelemetry integration and sample aggressively. |
### Wrap‑up
With these pieces you now have a full‑stack real‑time pipeline:
-
Server – Hot Chocolate with Redis (or in‑memory) subscriptions
-
Client – Strawberry Shake streams that deserialize directly into C# records
Add a single line of code at each mutation to eventSender.SendAsync(...) and every connected UI updates itself—no SignalR, no polling, no fuss.
Final Thoughts
GraphQL isn’t a silver bullet, but when you need:
-
chat‑style real‑time updates
-
mobile apps that loathe over‑fetching
-
complex UIs that would otherwise juggle many REST calls
…it’s a game‑changer.
With Hot Chocolate the server setup is minutes, not hours, and Strawberry Shake gives you a first‑class .NET experience on the client. Give it a try on your next side project and see how it feels—chances are you’ll never craft a fleet of brittle REST endpoints again.
Happy querying! 🚀

No comments:
Post a Comment