How does dependency injection work identically for both Blazor components and MVC controllers, given they're both hosted in the same ASP.NET Core DI container?
Short answer
Both consume the exact same IServiceCollection registrations from Program.cs -- a service registered once via AddScoped/AddSingleton/AddTransient is resolvable both in an MVC controller's constructor and a Blazor component's @inject directive, since both ultimately resolve from…
Advertisement
AModel answer
Both consume the exact same IServiceCollection registrations from Program.cs -- a service registered once via AddScoped/AddSingleton/AddTransient is resolvable both in an MVC controller's constructor and a Blazor component's @inject directive, since both ultimately resolve from the same underlying DI container, though the practical meaning of 'Scoped' differs (per-HTTP-request for MVC, per-user-circuit for Blazor Server, or effectively per-app-instance for Blazor WebAssembly).
// Registered once, used in both paradigms
builder.Services.AddScoped<IProductService, ProductService>();
// MVC controller
public class ProductsController(IProductService service) : ControllerBase { }
// Blazor component
@inject IProductService ProductServiceReal-world example
A shared IProductService is injected identically into both a legacy MVC controller serving a JSON API and a new Blazor component rendering an interactive product list, with both consuming the exact same business logic without duplication.
Likely follow-ups
- How does Scoped lifetime differ in practical meaning between MVC requests and Blazor Server circuits?
- What happens if a service assumes HTTP request-scoped behavior but is used in Blazor Server?
Related topics