Visual Programming
Insturctor:Eeman Fatima
BSCS-IV-A
Lab Manual: Dependency Injection and Services in Blazor
What Are Services in Blazor?
Services in Blazor are reusable components that encapsulate logic and data so they
can be used across different parts of the application. Instead of writing the same logic
multiple times, we create a service once and use it wherever needed.
Dependency injection (DI) is a technique for accessing services configured in a
central location:
Framework-registered services can be injected directly into Razor components.
Blazor apps define and register custom services and make them available throughout
the app via DI.
Create a New Blazor Web App (Server Interactivity):
Step 1: Register and Inject a Simple Service
Create a Counter Service:
In the project, create a new folder called Service.
Inside the Services folder, create a new class called [Link]:
Register the Service:
Open [Link] and register the CounterService as a Singleton:
Observe Counter Component, when moved back from another component loses/
forgets its state.
Lets see what Services can do for state management.
Use the Service in a Component:
Open Pages/[Link] and modify it to use the CounterService:
@inject CounterService CounterService
Now run project again and observe that counter doesn’t lose state after navigation to
other components.
Step 2: Demonstrate Service Lifetimes Using CounterService
Understanding Service Lifetimes in Blazor (or any .NET Dependency Injection System)
In Blazor (and .NET in general), Dependency Injection (DI) allows you to register and
manage services with different lifetimes. The three main lifetimes are:
Singleton
A single instance is created and shared across the entire application.
Created once and reused everywhere.
Example: App settings, like theme that developer has changed that must persist along all users.
Scoped
A new instance is created for each scope (in Blazor WebAssembly, this means per user
session).
Useful for services that need to maintain state per request or session.
Example: A shopping cart service that needs to persist for a single user but reset when they
leave the app (but in blazor server projects, one user session is bind to one browser window,
unless user closes the tab the session maintains)
Transient
A new instance is created every time it is requested.
Useful for lightweight, stateless services.
Example: A service that formats dates, where creating a new instance every time is fine.
For example; in a coffee shop app, every customer has unique and independent instance of
Order Service.
Scenario: Multi-Counter System
Imagine a web app with three counters:
Singleton Counter → Shared across all users and sessions.
Scoped Counter → Unique per user session (persists until the user disconnects/closes tab).
Transient Counter → Resets on every action.
Step 1: Make a new blazor web app (Server Interactivity)
Make a folder and add 3 new .cs files for each service
Step 2:
Add code in each service to handle count
Step 3:
Register Services:in [Link]
Run your app, increment all counts to equal
Move to different components and come back and observe values
Observe that Transient changes with every interaction between components
Now open a new tab in chrome and go to same URL as your app is opened in
Observe how Singleton is maintained in second user session on separate tab while Scoped resets
Opening in Edge:
Lab Task 1:
Remember you made a todo list in last lab. When you move between components
in that todo app, your tasks get lost. Modify that project to use that TaskItem
class as service instead of a simple class and register that service as Scoped or
Singleton (your choice) so that todo list may persist through entire session (in
case of scoped) or through entire app (in case of singleton). Use DI to inject that
service in your todo component.
Lab Task 2:
Implementing an AuthService for User Registration and Sign-In in Blazor Web
App.
Which Service Lifetime to Choose?
Scoped (Recommended) → Authentication state should be specific to each user
session.
Singleton ( Not Recommended) → Would share authentication across all users.
Transient (Not Recommended) → Would lose authentication state on each request.
Task 1: Create an AuthService (Scoped)
Create a folder Service in the Blazor project.
Inside Service, create a new file: [Link].
Implement authentication logic in [Link]:
using [Link]; is used for managing user authentication and
authorization in .NET applications, including Blazor. It provides a way to store and
retrieve user identity details securely.
What Are Claims?
A claim is a piece of information (like username, email, or role) that defines the user’s
identity. It is often used in authentication systems to store and verify user details.
ContainsKey and TryGetValue are built-in methods of the Dictionary<TKey,
TValue> class in C#.
private Dictionary<string, string> _users = new() How
{ Dictionary
{ "alice", "password123" }, stores data in
{ "bob", "securePass" } pairs
};
TryGetValue(username, out var storedPassword):
If username exists, storedPassword stores the corresponding password.
If username does not exist, storedPassword is set to null, and the condition fails.
Task 2: Register the Service in [Link]
Add the Scoped AuthService in [Link]:
Task 3: Create Authentication UI
Login & Registration Page ([Link])
Step 4: Navigate to [Link] after login and add logout button