Services in Blazor

By Syncfusion®, Inc. · Last updated

Services in Blazor: what a service is and why it helps, separating logic from UI, a user service with CRUD methods, service interfaces, registering and injecting services, Transient, Scoped and Singleton lifetimes, and sharing logic across components.

What you will learn

  • Move logic out of components into a service
  • Build a user service with CRUD methods and an interface
  • Register a service with DI and use it in components
  • Pick the right lifetime: Transient, Scoped or Singleton

Services Overview

  • In Dependency Injection, components asked the DI container for objects. Most of those objects are services.
  • A service is a C# class that does one job for your app, like loading customers, saving an order or working out a bill.
  • A service has no HTML. Components show things on the screen. Services do the work behind them.

Real-World Example:

  • Ravi keeps a list of his regular customers: their names and phone numbers.
  • The Customers page shows the list, the Order page picks a customer, and the Reports page counts them.
  • One UserService holds the list and the rules. All three pages use it.

Three pages, Customers, Order and Reports, each with an arrow to one shared box called UserService, which holds the customer list and the rules.

Customers.razor

Order.razor

Reports.razor

UserService customer list + rules no HTML

One service does the work. Many pages use it.

Benefits of Services

  • Reuse: write the code once, use it in every page.
  • One place to change: when a rule changes, like "phone numbers need 10 digits", you change one class.
  • Smaller components: pages only show data and react to clicks, so they are easier to read.
  • Easy swapping: a page can use one class today and a different class later, with no change to the page.
  • Easy testing: you can test a service in plain C#, without a browser.

Separating Logic from UI

  • UI (user interface) is what the user sees and clicks: the .razor markup.
  • Logic is the work behind it: rules, calculations and keeping data.
  • When both live in one component, the component grows big, and other pages cannot reuse the logic.
  • The fix: move the logic into a service, and let the component call it.

In the below example, the list and the "add a customer" rule live inside the page. It works, but no other page can use them.

  • In the rest of this lesson, the list and its rules move into a UserService.

Creating Services

Service Folder Structure

  • Put services in a Services folder, and the data classes they use in a Models folder.
  • A model is a small class that only holds data, like User with Name and Phone.
  • Each service usually has two files: the interface (IUserService.cs) and the class (UserService.cs).

A folder tree. BlazorApp contains Components/Pages/Customers.razor, Models/User.cs, Services/IUserService.cs, Services/UserService.cs and Program.cs. Notes: pages show data, models hold data, services do the work, Program.cs registers the service.

📁 BlazorApp 📁 Components/Pages 📄 Customers.razor 📁 Models 📄 User.cs 📁 Services 📄 IUserService.cs 📄 UserService.cs 📄 Program.cs ← shows the data (UI) ← holds the data ← does the work ← registers the service

Pages, models and services each have their own folder.

User Service with CRUD Operations

  • CRUD stands for the four basic jobs with data: Create (add), Read (get), Update (change) and Delete (remove).
  • UserService keeps the customers in a List<User> and has one method for each job.
  • Here the list lives in the service, in memory.

In the below example, UserService.cs has the CRUD methods. Customers.razor tries them. For now, it makes the service with new. You will inject it soon.

  • Click each button and watch the list. The page has no list and no rules of its own any more.

Service Interfaces (IUserService)

  • In Dependency Injection, you met interfaces: a list of methods a class promises to have.
  • IUserService lists the five CRUD methods. UserService keeps the promise with : IUserService.
  • Pages ask for IUserService, not UserService. So you can later swap in another class that keeps the same promise, like a TestUserService with sample users, and no page changes.

If the class misses a method from the interface, the build fails. The interface is a checklist the compiler checks for you.

Registering Services with DI

  • Register the service once in Program.cs, before builder.Build().
  • Read the line builder.Services.AddScoped<IUserService, UserService>(); in parts:

    • builder.Services is the DI container's list, where you add everything components can ask for.
    • AddScoped is the method that adds one entry to that list. Its name also sets the lifetime (how long one object lives). Lifetimes are explained below.
    • <IUserService, UserService> means: "when someone asks for IUserService, give them a UserService". Interface first, class second.

Using Services in Components

  • Inject the service with @inject IUserService Users, as you learned in Dependency Injection.
  • Then call its methods in markup and in @code, like Users.GetAll() and Users.Add(...).

The code boxes cannot change Program.cs. So in the box below, Services/AppServices.cs stands in for it: it registers IUserService in a small DI container, and the page asks that container. Everything else is the same as in a real app.

AppServices exists only because the code box cannot edit Program.cs. In your own app, do not write it. Register in Program.cs and use @inject.

In the below example, Customers.razor gets IUserService and uses it to list, add and delete customers.

Object Lifetimes

  • An object lifetime is how long the DI container keeps one object and shares it.
  • You choose it when you register: AddTransient, AddScoped or AddSingleton.

Animation with two users, Asha and Ravi, each asking for a service twice. Transient row: four separate objects. Scoped row: Asha gets one object twice, Ravi gets another. Singleton row: everyone gets the same single object.

Transient Scoped Singleton Asha asks twice Ravi asks twice

4 objects

2 objects

one shared object 1 object

Transient: new every time. Scoped: one per user. Singleton: one for everyone.

Transient

  • A new object every time someone asks.
  • Good for small helpers that keep no data, like a price calculator.

Scoped

  • One object per user. Blazor gives each user their own area, called a scope. Every component that user sees gets the same object.
  • Good for one user's data, like their cart or login. This is the usual choice for services like UserService.

Singleton

  • One object for the whole app, shared by every user.
  • Good for data that is the same for everyone and does not change often, like the tea menu.

In the below example, three counters are registered with the three lifetimes. Asha's scope asks twice and Ravi's scope asks once. Each ask adds one visit.

  • Transient: 1 and 1, because every ask makes a new counter.
  • Scoped: Asha's 2 visits share one counter, Ravi has his own: 2 and 1.
  • Singleton: everyone shares one counter: 3 and 3.

In a server app, never keep one user's data in a singleton. Every user would see it. Use scoped for user data.

Sharing Logic Across Components

  • When two components need the same rule, put the rule in one service and let both use it.
  • Then a change to the rule updates every component at once.

In the below example, PriceService.cs has the rule "10% off from 3 cups". MenuCard.razor and BillSummary.razor both use it, so their prices always agree. Change the rule to 20% and run again.

Common mistakes

MistakeWrong ideaCorrect ideaWhat goes wrong
HTML or components inside a serviceA service can draw the pageKeep markup in .razor files. Services only do workThe service cannot be reused or tested
The same rule copied into many componentsCopying is quickerPut the rule in one servicePages show different results
Registering UserService but injecting IUserServiceEither name worksRegister the interface: AddScoped<IUserService, UserService>()"There is no registered service of type IUserService"
A class that misses a method of its interfaceThe interface is just a commentImplement every method it listsA build error
One user's data in a singleton on the serverSingleton means one per userUse AddScoped for user dataEvery user sees the same data
A singleton that needs a scoped serviceAny lifetime can use any otherA singleton can only use singleton or transient servicesAn error when the app starts

Check Yourself

Exercises

What to Remember

  • A service is a C# class that does one job for the app. It has no HTML.
  • Services give reuse, one place to change, smaller components, easy swapping and easy testing.
  • Keep the UI in .razor files and the logic in services.
  • Put services in Services/ and data classes in Models/. CRUD means Create, Read, Update and Delete.
  • Write an interface like IUserService, register it with builder.Services.AddScoped<IUserService, UserService>(); and inject it with @inject IUserService Users.
  • Lifetimes: Transient (new each time), Scoped (one per user), Singleton (one for everyone).
  • Put shared rules in one service, so every component gives the same answer.

Next: Database Handling