# Services

Course: [Blazor](https://www.devtutorials.ai/learn/blazor) · Section: Data Access
Source: https://www.devtutorials.ai/learn/blazor/data-access/services

> 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.

## 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.

<figure className="blz-fig">
<svg viewBox="0 0 640 195" role="img" aria-labelledby="fig-sv-many">
  <title id="fig-sv-many">Three pages, Customers, Order and Reports, each with an arrow to one shared box called UserService, which holds the customer list and the rules.</title>
  <defs><marker id="fig-sv-many-a" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto"><path d="M0 0 L10 5 L0 10 z" style={{ fill: "var(--muted)" }} /></marker></defs>
  <rect className="blu" x="20" y="20" width="170" height="40" rx="8" />
  <text className="t m" x="105" y="45" textAnchor="middle" style={{ fontSize: 12 }}>Customers.razor</text>
  <rect className="blu" x="20" y="80" width="170" height="40" rx="8" />
  <text className="t m" x="105" y="105" textAnchor="middle" style={{ fontSize: 12 }}>Order.razor</text>
  <rect className="blu" x="20" y="140" width="170" height="40" rx="8" />
  <text className="t m" x="105" y="165" textAnchor="middle" style={{ fontSize: 12 }}>Reports.razor</text>
  <rect className="pur" x="400" y="55" width="220" height="90" rx="12" />
  <text className="t m" x="510" y="85" textAnchor="middle" style={{ fontSize: 13, fontWeight: 700 }}>UserService</text>
  <text className="t" x="510" y="108" textAnchor="middle" style={{ fontSize: 11 }}>customer list + rules</text>
  <text className="t" x="510" y="126" textAnchor="middle" style={{ fontSize: 11 }}>no HTML</text>
  <path className="line" d="M190 40 L396 82" markerEnd="url(#fig-sv-many-a)" />
  <path className="line" d="M190 100 H396" markerEnd="url(#fig-sv-many-a)" />
  <path className="line" d="M190 160 L396 120" markerEnd="url(#fig-sv-many-a)" />
</svg>
<figcaption>One service does the work. Many pages use it.</figcaption>
</figure>

## 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.

<button @onclick="AddGuest">Add guest</button>

@foreach (var name in users)
{
      <p>@name</p>
}

@code {
      // Data and rules stuck inside one page
      private List<string> users = new() { "Asha", "Ravi" };

      private void AddGuest()
      {
          if (users.Count < 5)
              users.Add($"Guest {users.Count + 1}");
      }
}
`,
  }}
/>

- 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`).

<figure className="blz-fig">
<svg viewBox="0 0 640 220" role="img" aria-labelledby="fig-sv-tree">
  <title id="fig-sv-tree">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.</title>
  <defs><marker id="fig-sv-tree-a" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto"><path d="M0 0 L10 5 L0 10 z" style={{ fill: "var(--muted)" }} /></marker></defs>
  <rect className="box" x="20" y="10" width="600" height="200" rx="10" />
  <text className="t m" x="40" y="36" style={{ fontSize: 13, fontWeight: 700 }}>📁 BlazorApp</text>
  <text className="t m" x="64" y="64" style={{ fontSize: 12 }}>📁 Components/Pages</text>
  <text className="t m" x="96" y="86" style={{ fontSize: 12 }}>📄 Customers.razor</text>
  <text className="t m" x="64" y="112" style={{ fontSize: 12 }}>📁 Models</text>
  <text className="t m" x="96" y="134" style={{ fontSize: 12 }}>📄 User.cs</text>
  <text className="t m" x="64" y="160" style={{ fontSize: 12 }}>📁 Services</text>
  <text className="t m" x="96" y="182" style={{ fontSize: 12 }}>📄 IUserService.cs  📄 UserService.cs</text>
  <text className="t m" x="64" y="204" style={{ fontSize: 12 }}>📄 Program.cs</text>
  <text className="t" x="380" y="86" style={{ fontSize: 11 }}>← shows the data (UI)</text>
  <text className="t" x="380" y="134" style={{ fontSize: 11 }}>← holds the data</text>
  <text className="t" x="380" y="182" style={{ fontSize: 11 }}>← does the work</text>
  <text className="t" x="380" y="204" style={{ fontSize: 11 }}>← registers the service</text>
</svg>
<figcaption>Pages, models and services each have their own folder.</figcaption>
</figure>

### User Service with CRUD Operations

- **CRUD** stands for the four basic jobs with data: **C**reate (add), **R**ead (get), **U**pdate (change) and **D**elete (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.

<button @onclick='() => service.Update(new User { Id = 1, Name = "Asha K", Phone = "98400 11111" })'>Update Asha</button>
<button @onclick="() => service.Delete(2)">Delete Ravi</button>

@foreach (var u in service.GetAll())
{
      <p>#@u.Id @u.Name (@u.Phone)</p>
}

@code {
      // For now only. Next: get it from DI.
      private UserService service = new();
}
`,
    "Services/UserService.cs": `using BlazorApp.Models;

namespace BlazorApp.Services;

public class UserService : IUserService
{
      private readonly List<User> users = new()
      {
          new User { Id = 1, Name = "Asha", Phone = "98400 11111" },
          new User { Id = 2, Name = "Ravi", Phone = "98400 22222" },
      };
      private int nextId = 3;

      // Read
      public List<User> GetAll() => users;
      public User? GetById(int id) => users.FirstOrDefault(u => u.Id == id);

      // Create
      public void Add(User user)
      {
          user.Id = nextId++;
          users.Add(user);
      }

      // Update
      public void Update(User user)
      {
          var old = GetById(user.Id);
          if (old != null)
          {
              old.Name = user.Name;
              old.Phone = user.Phone;
          }
      }

      // Delete
      public void Delete(int id) => users.RemoveAll(u => u.Id == id);
}
`,
    "Services/IUserService.cs": `using BlazorApp.Models;

namespace BlazorApp.Services;

public interface IUserService
{
      List<User> GetAll();
      User? GetById(int id);
      void Add(User user);
      void Update(User user);
      void Delete(int id);
}
`,
    "Models/User.cs": `namespace BlazorApp.Models;

public class User
{
      public int Id { get; set; }
      public string Name { get; set; } = "";
      public string Phone { get; set; } = "";
}
`,
  }}
/>

- 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.

      <input @bind="name" placeholder="Name" />
      <button @onclick="Add">Add</button>
</p>

@foreach (var u in Users.GetAll())
{
      <p>@u.Name <button @onclick="() => Users.Delete(u.Id)">Delete</button></p>
}

@code {
      // In your app: @inject IUserService Users
      private IUserService Users = AppServices.Container.GetRequiredService<IUserService>();
      private string name = "";

      private void Add()
      {
          if (name != "") Users.Add(new User { Name = name });
          name = "";
      }
}
`,
    "Services/AppServices.cs": `using Microsoft.Extensions.DependencyInjection;

namespace BlazorApp.Services;

// Stands in for Program.cs, which the code box cannot change.
public static class AppServices
{
      public static IServiceProvider Container { get; } = Build();

      private static IServiceProvider Build()
      {
          var services = new ServiceCollection();
          services.AddSingleton<IUserService, UserService>(); // like builder.Services.Add...
          return services.BuildServiceProvider();
      }
}
`,
    "Services/UserService.cs": `using BlazorApp.Models;

namespace BlazorApp.Services;

public class UserService : IUserService
{
      private readonly List<User> users = new()
      {
          new User { Id = 1, Name = "Asha", Phone = "98400 11111" },
          new User { Id = 2, Name = "Ravi", Phone = "98400 22222" },
      };
      private int nextId = 3;

      // Read
      public List<User> GetAll() => users;
      public User? GetById(int id) => users.FirstOrDefault(u => u.Id == id);

      // Create
      public void Add(User user)
      {
          user.Id = nextId++;
          users.Add(user);
      }

      // Update
      public void Update(User user)
      {
          var old = GetById(user.Id);
          if (old != null)
          {
              old.Name = user.Name;
              old.Phone = user.Phone;
          }
      }

      // Delete
      public void Delete(int id) => users.RemoveAll(u => u.Id == id);
}
`,
    "Services/IUserService.cs": `using BlazorApp.Models;

namespace BlazorApp.Services;

public interface IUserService
{
      List<User> GetAll();
      User? GetById(int id);
      void Add(User user);
      void Update(User user);
      void Delete(int id);
}
`,
    "Models/User.cs": `namespace BlazorApp.Models;

public class User
{
      public int Id { get; set; }
      public string Name { get; set; } = "";
      public string Phone { get; set; } = "";
}
`,
  }}
/>

## 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`.

<figure className="blz-fig">
<svg viewBox="0 0 640 175" role="img" aria-labelledby="fig-sv-life">
  <title id="fig-sv-life">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.</title>
  <defs><marker id="fig-sv-life-a" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto"><path d="M0 0 L10 5 L0 10 z" style={{ fill: "var(--muted)" }} /></marker></defs>
  <text className="t m" x="20" y="34" style={{ fontSize: 12, fontWeight: 700 }}>Transient</text>
  <text className="t m" x="20" y="94" style={{ fontSize: 12, fontWeight: 700 }}>Scoped</text>
  <text className="t m" x="20" y="154" style={{ fontSize: 12, fontWeight: 700 }}>Singleton</text>
  <text className="t" x="230" y="14" textAnchor="middle" style={{ fontSize: 11 }}>Asha asks twice</text>
  <text className="t" x="470" y="14" textAnchor="middle" style={{ fontSize: 11 }}>Ravi asks twice</text>
  <circle cx="190" cy="30" r="12" className="org" /><circle cx="270" cy="30" r="12" className="org" />
  <circle cx="430" cy="30" r="12" className="org" /><circle cx="510" cy="30" r="12" className="org" />
  <text className="t" x="600" y="34" textAnchor="end" style={{ fontSize: 11 }}>4 objects</text>
  <rect className="grn" x="170" y="78" width="120" height="26" rx="13" />
  <rect className="blu" x="410" y="78" width="120" height="26" rx="13" />
  <text className="t" x="600" y="96" textAnchor="end" style={{ fontSize: 11 }}>2 objects</text>
  <rect className="pur" x="170" y="138" width="360" height="26" rx="13"><animate attributeName="opacity" values="0.4;1;0.4" dur="3s" repeatCount="indefinite" /></rect>
  <text className="t m" x="350" y="156" textAnchor="middle" style={{ fontSize: 11 }}>one shared object</text>
  <text className="t" x="600" y="156" textAnchor="end" style={{ fontSize: 11 }}>1 object</text>
</svg>
<figcaption>Transient: new every time. Scoped: one per user. Singleton: one for everyone.</figcaption>
</figure>

### 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.

}

@code {
      private List<string> lines = new();

      protected override void OnInitialized()
      {
          var services = new ServiceCollection();
          services.AddTransient<TransientCounter>();
          services.AddScoped<ScopedCounter>();
          services.AddSingleton<SingletonCounter>();
          var container = services.BuildServiceProvider();

          lines.Add(Visits<TransientCounter>(container, "Transient"));
          lines.Add(Visits<ScopedCounter>(container, "Scoped"));
          lines.Add(Visits<SingletonCounter>(container, "Singleton"));
      }

      private static string Visits<T>(IServiceProvider container, string label) where T : Counter
      {
          using var asha = container.CreateScope();
          using var ravi = container.CreateScope();
          asha.ServiceProvider.GetRequiredService<T>().Visit();
          var ashaCounter = asha.ServiceProvider.GetRequiredService<T>();
          ashaCounter.Visit();
          var raviCounter = ravi.ServiceProvider.GetRequiredService<T>();
          raviCounter.Visit();
          return $"{label}: Asha's counter = {ashaCounter.Count}, Ravi's counter = {raviCounter.Count}";
      }

      private class Counter { public int Count; public void Visit() => Count++; }
      private class TransientCounter : Counter { }
      private class ScopedCounter : Counter { }
      private class SingletonCounter : Counter { }
}
`,
  }}
/>

- **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.

`,
    "Services/PriceService.cs": `namespace BlazorApp.Services;

public class PriceService
{
      public int PricePerCup(int cups)
      {
          int price = 20;
          if (cups >= 3) price -= price * 10 / 100; // 10% off from 3 cups
          return price;
      }
}
`,
    "Services/AppServices.cs": `using Microsoft.Extensions.DependencyInjection;

namespace BlazorApp.Services;

// Stands in for Program.cs, which the code box cannot change.
public static class AppServices
{
      public static IServiceProvider Container { get; } = Build();

      private static IServiceProvider Build()
      {
          var services = new ServiceCollection();
          services.AddSingleton<PriceService>();
          return services.BuildServiceProvider();
      }
}
`,
    "Components/MenuCard.razor": `@using BlazorApp.Services
@using Microsoft.Extensions.DependencyInjection

<p>Menu: Masala Tea ₹20, or ₹@Prices.PricePerCup(3) each for 3 or more</p>

@code {
      // In your app: @inject PriceService Prices
      private PriceService Prices = AppServices.Container.GetRequiredService<PriceService>();
}
`,
    "Components/BillSummary.razor": `@using BlazorApp.Services
@using Microsoft.Extensions.DependencyInjection

<p>Bill: @Cups cups × ₹@Prices.PricePerCup(Cups) = ₹@(Cups * Prices.PricePerCup(Cups))</p>

@code {
      [Parameter] public int Cups { get; set; }

      // In your app: @inject PriceService Prices
      private PriceService Prices = AppServices.Container.GetRequiredService<PriceService>();
}
`,
  }}
/>

## Common mistakes

<div className="tscroll">

| Mistake | Wrong idea | Correct idea | What goes wrong |
|---|---|---|---|
| HTML or components inside a service | A service can draw the page | Keep markup in `.razor` files. Services only do work | The service cannot be reused or tested |
| The same rule copied into many components | Copying is quicker | Put the rule in one service | Pages show different results |
| Registering `UserService` but injecting `IUserService` | Either name works | Register the interface: `AddScoped<IUserService, UserService>()` | "There is no registered service of type IUserService" |
| A class that misses a method of its interface | The interface is just a comment | Implement every method it lists | A build error |
| One user's data in a singleton on the server | Singleton means one per user | Use `AddScoped` for user data | Every user sees the same data |
| A singleton that needs a scoped service | Any lifetime can use any other | A singleton can only use singleton or transient services | An error when the app starts |

</div>

## 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**
