Posts

Showing posts from April, 2020

Blazor: Scoping services to a component

If you want your Blazor component to have its own dependency injection scope, so you can inject new instances of services and have those services disposed of when the component is disposed, then do the following: First, copy and paste the code below into your application.  Then descend your component from ScopedComponentBase . Finally, decorate your dependency properties with [InjectScoped] rather than [Inject] or @inject . For example @inherits ScopedComponentBase @code { [InjectScoped] private WeatherService MyWeatherService { get; set; } } Here is the code you need using Microsoft.AspNetCore.Components; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace BlazorApp130.Shared { public abstract class ScopedComponentBase : OwningComponentBase<IServiceProvider> { protected override void OnInitialized() { base.OnInitialized(); DependencyInjector.InjectDependencies(