Author : MD TAREQ HASSAN | Updated : 2020/09/08

Problem with existing scopes

AddDbContextFactory in Startup

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
	services.AddRazorPages();
	services.AddServerSideBlazor();

	// ... ... ...

	//var dbConnectionString = AzureUtil.GetKeyVaultSecretValue(keyVaultUri: Configuration[Constants.Azure.KeyVaultIdentifier], key: DB.ConnectionStringIdentifier);
	var dbConnectionString = Configuration["DBConnectionString"];
	
	services.AddDbContextFactory<EmailAddressDbContext>(options => options.UseSqlServer(dbConnectionString));

	// ... ... ...
}

DbContext Property and IDisposible in BaseComponent

Components/BaseComponent.cs

using Microsoft.AspNetCore.Components;
using System;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using AutoMapper;
using System.Threading.Tasks;

public class BaseComponent: ComponentBase, IDisposable
{
	// ... ... ...

	[Inject]
	protected IDbContextFactory<FooDbContext> DbContextFactory { get; set; }
	
	protected FooDbContext DbContext { get; set; }

	[Inject]
	protected IMapper Mapper { get; set; }
	
	// ... ... ...

	protected void InitDependencies()
	{
		DbContext = DbContextFactory.CreateDbContext();
		
		// setup logger, other things
	}

	// ... ... ...
	
	public void Dispose()
	{
		DbContext?.Dispose(); // DbContext will be disposed automatically
	}
}

Using DbContext in component

Pages/delete.razor.cs

public class DeleteBase : BaseComponent
{
	[Parameter]
	public int Id { get; set; }

    // ... ... ...

	protected override async Task OnInitializedAsync()
	{
		InitDependencies();

		// ... ... ...
		
		// perform async operation
	}


	protected async Task PerformDeletion()
	{
		
		// ... ... ...

		try
		{
			var itemToDelete = await DbContext.Items.FindAsync(Id);

			// EF Core Operations
			DbContext.Items.Remove(itemToDelete);
			await DbContext.SaveChangesAsync();

			NavigationManager.NavigateTo("/items?deleted");
		}
		catch (Exception)
		{
			// handle exception, show error
		}
	}
	
	// ... ... ...
}