Skip to content

Commit

Permalink
Use DbContextFactory (fixes #45)
Browse files Browse the repository at this point in the history
  • Loading branch information
linkdotnet committed Sep 19, 2022
1 parent 9ab463b commit 31f2662
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 10 deletions.
10 changes: 7 additions & 3 deletions src/LinkDotNet.Blog.Infrastructure/Persistence/Sql/Repository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,16 @@ namespace LinkDotNet.Blog.Infrastructure.Persistence.Sql;
public class Repository<TEntity> : IRepository<TEntity>
where TEntity : Entity
{
private readonly BlogDbContext blogDbContext;
private readonly IDbContextFactory<BlogDbContext> dbContextFactory;

public Repository(BlogDbContext blogDbContext)
public Repository(IDbContextFactory<BlogDbContext> dbContextFactory)
{
this.blogDbContext = blogDbContext;
this.dbContextFactory = dbContextFactory;
}

public async ValueTask<TEntity> GetByIdAsync(string id)
{
await using var blogDbContext = await dbContextFactory.CreateDbContextAsync();
return await blogDbContext.Set<TEntity>().SingleOrDefaultAsync(b => b.Id == id);
}

Expand All @@ -30,6 +31,7 @@ public async ValueTask<IPagedList<TEntity>> GetAllAsync(
int page = 1,
int pageSize = int.MaxValue)
{
await using var blogDbContext = await dbContextFactory.CreateDbContextAsync();
var entity = blogDbContext.Set<TEntity>().AsNoTracking().AsQueryable();

if (filter != null)
Expand All @@ -49,6 +51,7 @@ public async ValueTask<IPagedList<TEntity>> GetAllAsync(

public async ValueTask StoreAsync(TEntity entity)
{
await using var blogDbContext = await dbContextFactory.CreateDbContextAsync();
if (string.IsNullOrEmpty(entity.Id))
{
await blogDbContext.Set<TEntity>().AddAsync(entity);
Expand All @@ -63,6 +66,7 @@ public async ValueTask StoreAsync(TEntity entity)

public async ValueTask DeleteAsync(string id)
{
await using var blogDbContext = await dbContextFactory.CreateDbContextAsync();
var entityToDelete = await GetByIdAsync(id);
if (entityToDelete != null)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,19 +12,26 @@ namespace LinkDotNet.Blog.IntegrationTests;
public abstract class SqlDatabaseTestBase<TEntity> : IAsyncLifetime, IAsyncDisposable
where TEntity : Entity
{
private readonly Mock<IDbContextFactory<BlogDbContext>> dbContextFactory;

protected SqlDatabaseTestBase()
{
var options = new DbContextOptionsBuilder()
.UseSqlite(CreateInMemoryConnection())
.Options;
DbContext = new BlogDbContext(options);
Repository = new Repository<TEntity>(new BlogDbContext(options));
dbContextFactory = new Mock<IDbContextFactory<BlogDbContext>>();
dbContextFactory.Setup(d => d.CreateDbContextAsync(default))
.ReturnsAsync(() => new BlogDbContext(options));
Repository = new Repository<TEntity>(dbContextFactory.Object);
}

protected IRepository<TEntity> Repository { get; }

protected BlogDbContext DbContext { get; }

protected IDbContextFactory<BlogDbContext> DbContextFactory => dbContextFactory.Object;

public Task InitializeAsync()
{
return Task.CompletedTask;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
using LinkDotNet.Blog.Web.Features.Admin.Dashboard.Components;
using LinkDotNet.Blog.Web.Features.Admin.Dashboard.Services;
using Microsoft.AspNetCore.Components;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;

namespace LinkDotNet.Blog.IntegrationTests.Web.Features.Admin.Dashboard.Components;
Expand All @@ -22,8 +23,7 @@ public async Task ShouldShowCounts()
var blogPost = new BlogPostBuilder().WithTitle("I was clicked").WithLikes(2).Build();
await Repository.StoreAsync(blogPost);
using var ctx = new TestContext();
ctx.Services.AddScoped<IRepository<BlogPost>>(_ => new Repository<BlogPost>(DbContext));
ctx.Services.AddScoped<IRepository<UserRecord>>(_ => new Repository<UserRecord>(DbContext));
RegisterRepositories(ctx);
await SaveBlogPostArticleClicked(blogPost.Id, 10);

var cut = ctx.RenderComponent<VisitCountPerPage>();
Expand Down Expand Up @@ -58,8 +58,7 @@ public async Task ShouldFilterByDate()
await DbContext.SaveChangesAsync();
using var ctx = new TestContext();
ctx.ComponentFactories.Add<DateRangeSelector, FilterStubComponent>();
ctx.Services.AddScoped<IRepository<BlogPost>>(_ => new Repository<BlogPost>(DbContext));
ctx.Services.AddScoped<IRepository<UserRecord>>(_ => new Repository<UserRecord>(DbContext));
RegisterRepositories(ctx);
var cut = ctx.RenderComponent<VisitCountPerPage>();
var filter = new Filter { StartDate = new DateTime(2019, 1, 1), EndDate = new DateTime(2020, 12, 31) };

Expand Down Expand Up @@ -93,15 +92,20 @@ public async Task ShouldShowTotalClickCount()
await DbContext.UserRecords.AddRangeAsync(new[] { clicked1, clicked2, clicked3, clicked4 });
await DbContext.SaveChangesAsync();
using var ctx = new TestContext();
ctx.Services.AddScoped<IRepository<BlogPost>>(_ => new Repository<BlogPost>(DbContext));
ctx.Services.AddScoped<IRepository<UserRecord>>(_ => new Repository<UserRecord>(DbContext));
RegisterRepositories(ctx);

var cut = ctx.RenderComponent<VisitCountPerPage>();

cut.WaitForState(() => cut.FindAll("td").Any());
cut.Find("#total-clicks").Unwrap().TextContent.Should().Be("4 clicks in total");
}

private void RegisterRepositories(TestContextBase ctx)
{
ctx.Services.AddScoped<IRepository<BlogPost>>(_ => new Repository<BlogPost>(DbContextFactory));
ctx.Services.AddScoped<IRepository<UserRecord>>(_ => new Repository<UserRecord>(DbContextFactory));
}

private async Task SaveBlogPostArticleClicked(string blogPostId, int count)
{
var urlClicked = $"blogPost/{blogPostId}";
Expand Down

0 comments on commit 31f2662

Please sign in to comment.