Skip to content

Commit e47b51e

Browse files
committed
Refactor handlers to use DbContextFactory
Updated command and query handlers to utilize `IApplicationDbContextFactory` for improved database context management. This change creates a new context instance for each operation, enhancing asynchronous operations and promoting better design practices. The use of `await using var db = await _dbContextFactory.CreateAsync(cancellationToken);` ensures that all database operations are performed with a fresh context, improving testability and reducing context-related issues.
1 parent b5d23e2 commit e47b51e

9 files changed

Lines changed: 53 additions & 46 deletions

File tree

src/Templates/Commands/AddEdit/.cs.txt

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -37,36 +37,37 @@ public class AddEdit{itemname}Command: ICacheInvalidatorRequest<Result<int>>
3737
public class AddEdit{itemname}CommandHandler : IRequestHandler<AddEdit{itemname}Command, Result<int>>
3838
{
3939
private readonly IMapper _mapper;
40-
private readonly IApplicationDbContext _context;
40+
private readonly IApplicationDbContextFactory _dbContextFactory;
4141
public AddEdit{itemname}CommandHandler(
4242
IMapper mapper,
43-
IApplicationDbContext context)
43+
IApplicationDbContextFactory dbContextFactory)
4444
{
4545
_mapper = mapper;
46-
_context = context;
46+
_dbContextFactory = dbContextFactory;
4747
}
4848
public async Task<Result<int>> Handle(AddEdit{itemname}Command request, CancellationToken cancellationToken)
4949
{
50+
await using var db = await _dbContextFactory.CreateAsync(cancellationToken);
5051
if (request.Id > 0)
5152
{
52-
var item = await _context.{nameofPlural}.FindAsync(request.Id, cancellationToken);
53+
var item = await db.{nameofPlural}.FindAsync(request.Id, cancellationToken);
5354
if (item == null)
5455
{
5556
return await Result<int>.FailureAsync($"{itemname} with id: [{request.Id}] not found.");
5657
}
5758
item = _mapper.Map(request, item);
5859
// raise a update domain event
5960
item.AddDomainEvent(new {itemname}UpdatedEvent(item));
60-
await _context.SaveChangesAsync(cancellationToken);
61+
await db.SaveChangesAsync(cancellationToken);
6162
return await Result<int>.SuccessAsync(item.Id);
6263
}
6364
else
6465
{
6566
var item = _mapper.Map<{itemname}>(request);
6667
// raise a create domain event
6768
item.AddDomainEvent(new {itemname}CreatedEvent(item));
68-
_context.{nameofPlural}.Add(item);
69-
await _context.SaveChangesAsync(cancellationToken);
69+
db.{nameofPlural}.Add(item);
70+
await db.SaveChangesAsync(cancellationToken);
7071
return await Result<int>.SuccessAsync(item.Id);
7172
}
7273

src/Templates/Commands/Create/.cs.txt

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -34,21 +34,22 @@ public class Create{itemname}Command: ICacheInvalidatorRequest<Result<int>>
3434
public class Create{itemname}CommandHandler : IRequestHandler<Create{itemname}Command, Result<int>>
3535
{
3636
private readonly IMapper _mapper;
37-
private readonly IApplicationDbContext _context;
37+
private readonly IApplicationDbContextFactory _dbContextFactory;
3838
public Create{itemname}CommandHandler(
3939
IMapper mapper,
40-
IApplicationDbContext context)
40+
IApplicationDbContextFactory dbContextFactory)
4141
{
4242
_mapper = mapper;
43-
_context = context;
43+
_dbContextFactory = dbContextFactory;
4444
}
4545
public async Task<Result<int>> Handle(Create{itemname}Command request, CancellationToken cancellationToken)
4646
{
47+
await using var db = await _dbContextFactory.CreateAsync(cancellationToken);
4748
var item = _mapper.Map<{itemname}>(request);
4849
// raise a create domain event
4950
item.AddDomainEvent(new {itemname}CreatedEvent(item));
50-
_context.{nameofPlural}.Add(item);
51-
await _context.SaveChangesAsync(cancellationToken);
51+
db.{nameofPlural}.Add(item);
52+
await db.SaveChangesAsync(cancellationToken);
5253
return await Result<int>.SuccessAsync(item.Id);
5354
}
5455
}

src/Templates/Commands/Delete/.cs.txt

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -30,22 +30,23 @@ public class Delete{itemname}CommandHandler :
3030
IRequestHandler<Delete{itemname}Command, Result>
3131

3232
{
33-
private readonly IApplicationDbContext _context;
33+
private readonly IApplicationDbContextFactory _dbContextFactory;
3434
public Delete{itemname}CommandHandler(
35-
IApplicationDbContext context)
35+
IApplicationDbContextFactory dbContextFactory)
3636
{
37-
_context = context;
37+
_dbContextFactory = dbContextFactory;
3838
}
3939
public async Task<Result> Handle(Delete{itemname}Command request, CancellationToken cancellationToken)
4040
{
41-
var items = await _context.{nameofPlural}.Where(x=>request.Id.Contains(x.Id)).ToListAsync(cancellationToken);
41+
await using var db = await _dbContextFactory.CreateAsync(cancellationToken);
42+
var items = await db.{nameofPlural}.Where(x=>request.Id.Contains(x.Id)).ToListAsync(cancellationToken);
4243
foreach (var item in items)
4344
{
4445
// raise a delete domain event
4546
item.AddDomainEvent(new {itemname}DeletedEvent(item));
46-
_context.{nameofPlural}.Remove(item);
47+
db.{nameofPlural}.Remove(item);
4748
}
48-
await _context.SaveChangesAsync(cancellationToken);
49+
await db.SaveChangesAsync(cancellationToken);
4950
return await Result.SuccessAsync();
5051
}
5152

src/Templates/Commands/Import/.cs.txt

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -37,26 +37,26 @@ namespace {namespace};
3737
IRequestHandler<Create{nameofPlural}TemplateCommand, Result<byte[]>>,
3838
IRequestHandler<Import{nameofPlural}Command, Result<int>>
3939
{
40-
private readonly IApplicationDbContext _context;
40+
private readonly IApplicationDbContextFactory _dbContextFactory;
4141
private readonly IStringLocalizer<Import{nameofPlural}CommandHandler> _localizer;
4242
private readonly IExcelService _excelService;
4343
private readonly {itemname}Dto _dto = new();
4444
private readonly IMapper _mapper;
4545
public Import{nameofPlural}CommandHandler(
46-
IApplicationDbContext context,
46+
IApplicationDbContextFactory dbContextFactory,
4747
IMapper mapper,
4848
IExcelService excelService,
4949
IStringLocalizer<Import{nameofPlural}CommandHandler> localizer)
5050
{
51-
_context = context;
51+
_dbContextFactory = dbContextFactory;
5252
_localizer = localizer;
5353
_excelService = excelService;
5454
_mapper = mapper;
5555
}
5656
#nullable disable warnings
5757
public async Task<Result<int>> Handle(Import{nameofPlural}Command request, CancellationToken cancellationToken)
5858
{
59-
59+
await using var db = await _dbContextFactory.CreateAsync(cancellationToken);
6060
var result = await _excelService.ImportAsync(request.Data, mappers: new Dictionary<string, Func<DataRow, {itemname}Dto, object?>>
6161
{
6262
{importFuncExpression}
@@ -71,10 +71,10 @@ namespace {namespace};
7171
var item = _mapper.Map<{itemname}>(dto);
7272
// add create domain events if this entity implement the IHasDomainEvent interface
7373
// item.AddDomainEvent(new {itemname}CreatedEvent(item));
74-
await _context.{nameofPlural}.AddAsync(item, cancellationToken);
74+
await db.{nameofPlural}.AddAsync(item, cancellationToken);
7575
}
7676
}
77-
await _context.SaveChangesAsync(cancellationToken);
77+
await db.SaveChangesAsync(cancellationToken);
7878
return await Result<int>.SuccessAsync(result.Data.Count());
7979
}
8080
else

src/Templates/Commands/Update/.cs.txt

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -36,27 +36,27 @@ public class Update{itemname}Command: ICacheInvalidatorRequest<Result<int>>
3636

3737
public class Update{itemname}CommandHandler : IRequestHandler<Update{itemname}Command, Result<int>>
3838
{
39-
private readonly IApplicationDbContext _context;
39+
private readonly IApplicationDbContextFactory _dbContextFactory;
4040
private readonly IMapper _mapper;
4141
public Update{itemname}CommandHandler(
4242
IMapper mapper,
43-
IApplicationDbContext context)
43+
IApplicationDbContextFactory dbContextFactory)
4444
{
45-
_context = context;
45+
_dbContextFactory = dbContextFactory;
4646
_mapper = mapper;
4747
}
4848
public async Task<Result<int>> Handle(Update{itemname}Command request, CancellationToken cancellationToken)
4949
{
50-
51-
var item = await _context.{nameofPlural}.FindAsync(request.Id, cancellationToken);
50+
await using var db = await _dbContextFactory.CreateAsync(cancellationToken);
51+
var item = await db.{nameofPlural}.FindAsync(request.Id, cancellationToken);
5252
if (item == null)
5353
{
5454
return await Result<int>.FailureAsync($"{itemname} with id: [{request.Id}] not found.");
5555
}
5656
item = _mapper.Map(request, item);
5757
// raise a update domain event
5858
item.AddDomainEvent(new {itemname}UpdatedEvent(item));
59-
await _context.SaveChangesAsync(cancellationToken);
59+
await db.SaveChangesAsync(cancellationToken);
6060
return await Result<int>.SuccessAsync(item.Id);
6161
}
6262
}

src/Templates/Queries/Export/.cs.txt

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -37,26 +37,27 @@ public class Export{nameofPlural}QueryHandler :
3737
IRequestHandler<Export{nameofPlural}Query, Result<byte[]>>
3838
{
3939
private readonly IMapper _mapper;
40-
private readonly IApplicationDbContext _context;
40+
private readonly IApplicationDbContextFactory _dbContextFactory;
4141
private readonly IExcelService _excelService;
4242
private readonly IStringLocalizer<Export{nameofPlural}QueryHandler> _localizer;
4343
private readonly {itemname}Dto _dto = new();
4444
public Export{nameofPlural}QueryHandler(
4545
IMapper mapper,
46-
IApplicationDbContext context,
46+
IApplicationDbContextFactory dbContextFactory,
4747
IExcelService excelService,
4848
IStringLocalizer<Export{nameofPlural}QueryHandler> localizer
4949
)
5050
{
5151
_mapper = mapper;
52-
_context = context;
52+
_dbContextFactory = dbContextFactory;
5353
_excelService = excelService;
5454
_localizer = localizer;
5555
}
5656
#nullable disable warnings
5757
public async Task<Result<byte[]>> Handle(Export{nameofPlural}Query request, CancellationToken cancellationToken)
5858
{
59-
var data = await _context.{nameofPlural}.ApplySpecification(request.Specification)
59+
await using var db = await _dbContextFactory.CreateAsync(cancellationToken);
60+
var data = await db.{nameofPlural}.ApplySpecification(request.Specification)
6061
.OrderBy($"{request.OrderBy} {request.SortDirection}")
6162
.ProjectTo<{itemname}Dto>(_mapper.ConfigurationProvider)
6263
.AsNoTracking()

src/Templates/Queries/GetAll/.cs.txt

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -30,19 +30,20 @@ public class GetAll{nameofPlural}Query : ICacheableRequest<IEnumerable<{itemname
3030
public class GetAll{nameofPlural}QueryHandler :
3131
IRequestHandler<GetAll{nameofPlural}Query, IEnumerable<{itemname}Dto>>
3232
{
33-
private readonly IApplicationDbContext _context;
33+
private readonly IApplicationDbContextFactory _dbContextFactory;
3434
private readonly IMapper _mapper;
3535
public GetAll{nameofPlural}QueryHandler(
3636
IMapper mapper,
37-
IApplicationDbContext context)
37+
IApplicationDbContextFactory dbContextFactory)
3838
{
3939
_mapper = mapper;
40-
_context = context;
40+
_dbContextFactory = dbContextFactory;
4141
}
4242

4343
public async Task<IEnumerable<{itemname}Dto>> Handle(GetAll{nameofPlural}Query request, CancellationToken cancellationToken)
4444
{
45-
var data = await _context.{nameofPlural}.ProjectTo<{itemname}Dto>(_mapper.ConfigurationProvider)
45+
await using var db = await _dbContextFactory.CreateAsync(cancellationToken);
46+
var data = await db.{nameofPlural}.ProjectTo<{itemname}Dto>(_mapper.ConfigurationProvider)
4647
.AsNoTracking()
4748
.ToListAsync(cancellationToken);
4849
return data;

src/Templates/Queries/GetById/.cs.txt

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -31,19 +31,20 @@ public class Get{itemname}ByIdQuery : ICacheableRequest<Result<{itemname}Dto>>
3131
public class Get{itemname}ByIdQueryHandler :
3232
IRequestHandler<Get{itemname}ByIdQuery, Result<{itemname}Dto>>
3333
{
34-
private readonly IApplicationDbContext _context;
34+
private readonly IApplicationDbContextFactory _dbContextFactory;
3535
private readonly IMapper _mapper;
3636
public Get{itemname}ByIdQueryHandler(
3737
IMapper mapper,
38-
IApplicationDbContext context)
38+
IApplicationDbContextFactory dbContextFactory)
3939
{
4040
_mapper = mapper;
41-
_context = context;
41+
_dbContextFactory = dbContextFactory;
4242
}
4343

4444
public async Task<Result<{itemname}Dto>> Handle(Get{itemname}ByIdQuery request, CancellationToken cancellationToken)
4545
{
46-
var data = await _context.{nameofPlural}.ApplySpecification(new {itemname}ByIdSpecification(request.Id))
46+
await using var db = await _dbContextFactory.CreateAsync(cancellationToken);
47+
var data = await db.{nameofPlural}.ApplySpecification(new {itemname}ByIdSpecification(request.Id))
4748
.ProjectTo<{itemname}Dto>(_mapper.ConfigurationProvider)
4849
.FirstAsync(cancellationToken) ?? throw new NotFoundException($"{itemname} with id: [{request.Id}] not found.");
4950
return await Result<{itemname}Dto>.SuccessAsync(data);

src/Templates/Queries/Pagination/.cs.txt

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -35,19 +35,20 @@ public class {nameofPlural}WithPaginationQuery : {itemname}AdvancedFilter, ICach
3535
public class {nameofPlural}WithPaginationQueryHandler :
3636
IRequestHandler<{nameofPlural}WithPaginationQuery, PaginatedData<{itemname}Dto>>
3737
{
38-
private readonly IApplicationDbContext _context;
38+
private readonly IApplicationDbContextFactory _dbContextFactory;
3939
private readonly IMapper _mapper;
4040
public {nameofPlural}WithPaginationQueryHandler(
4141
IMapper mapper,
42-
IApplicationDbContext context)
42+
IApplicationDbContextFactory dbContextFactory)
4343
{
4444
_mapper = mapper;
45-
_context = context;
45+
_dbContextFactory = dbContextFactory;
4646
}
4747

4848
public async Task<PaginatedData<{itemname}Dto>> Handle({nameofPlural}WithPaginationQuery request, CancellationToken cancellationToken)
4949
{
50-
var data = await _context.{nameofPlural}.OrderBy($"{request.OrderBy} {request.SortDirection}")
50+
await using var db = await _dbContextFactory.CreateAsync(cancellationToken);
51+
var data = await db.{nameofPlural}.OrderBy($"{request.OrderBy} {request.SortDirection}")
5152
.ProjectToPaginatedDataAsync<{itemname}, {itemname}Dto>(request.Specification,
5253
request.PageNumber,
5354
request.PageSize,

0 commit comments

Comments
 (0)