Skip to content

Commit

Permalink
FIX Concurrency Problem in MediatR
Browse files Browse the repository at this point in the history
  • Loading branch information
mohammadKarimi committed Jan 11, 2024
1 parent b829ee7 commit 2307fae
Show file tree
Hide file tree
Showing 6 changed files with 15 additions and 28 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,12 @@
/// </summary>
public interface IApplicationDbContext
{
/// <summary>
/// Save all entities in to database.
/// </summary>
/// <returns></returns>
public Task<Result> SaveChangesAsync();

/// <summary>
/// Save all entities in to database.
/// </summary>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public Task<Result> SaveChangesAsync(CancellationToken cancellationToken);
public Task<int> SaveChangesAsync(CancellationToken cancellationToken);

DbSet<TEntity> Set<TEntity>() where TEntity : class;
}
2 changes: 1 addition & 1 deletion src/SwiftLink.Application/ConfigServices.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ public static IServiceCollection RegisterApplicationServices(this IServiceCollec
services.AddMediatR(config =>
{
config.RegisterServicesFromAssembly(Assembly.GetExecutingAssembly());
config.AddBehavior(typeof(IPipelineBehavior<,>), typeof(ValidationBehavior<,>));
// config.AddBehavior(typeof(IPipelineBehavior<,>), typeof(ValidationBehavior<,>));
});

services.AddScoped<IShortCodeGenerator, TimeBasedShortCodeGenerator>();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public class GenerateShortCodeCommandHandler(IApplicationDbContext dbContext,
private readonly IShortCodeGenerator _codeGenerator = codeGenerator;
private readonly AppSettings _options = options.Value;

public async Task<Result<object>> Handle(GenerateShortCodeCommand request, CancellationToken cancellationToken)
public async Task<Result<object>> Handle(GenerateShortCodeCommand request, CancellationToken cancellationToken = default)
{
var link = new Link
{
Expand All @@ -32,7 +32,7 @@ public async Task<Result<object>> Handle(GenerateShortCodeCommand request, Cance
_dbContext.Set<Link>().Add(link);

var dbResult = await _dbContext.SaveChangesAsync(cancellationToken);
if (dbResult.IsFailure)
if (dbResult > 1)
return Result<object>.Failure(Constants.Database.InsertFailed);

await _cache.Set(request.Url, JsonSerializer.Serialize(link), link.ExpirationDate);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
using SwiftLink.Domain.Common;
using Azure;
using SwiftLink.Domain.Common;
using SwiftLink.Infrastructure.Persistence.Extensions;
using System.Reflection;

namespace SwiftLink.Infrastructure.Persistence.Context;

public class ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : DbContext(options), IApplicationDbContext
public class ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: DbContext(options), IApplicationDbContext
{
protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder)
{
Expand All @@ -22,16 +24,11 @@ protected override void OnModelCreating(ModelBuilder modelBuilder)
relationship.DeleteBehavior = DeleteBehavior.NoAction;
}

public async Task<Result> SaveChangesAsync()
=> await SaveChangesAsync(default);

public new async Task<Result> SaveChangesAsync(CancellationToken cancellationToken)
public new async Task<Result> SaveChangesAsync(CancellationToken cancellationToken = default)
{
try
{
return await base.SaveChangesAsync(cancellationToken) is 0 ?
Result.Failure("Faile On Save into Database.") :
Result.Success();
return await base.SaveChangesAsync(cancellationToken) is 0 ? Result.Failure("Database operation failed :(") : Result.Success();
}
catch (Exception ex)
{
Expand Down
6 changes: 2 additions & 4 deletions src/SwiftLink.Presentation/Controllers/LinkController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,6 @@ public class LinkController : BaseController
{
[HttpPost]
[ShortenEndpointFilter]
public JsonResult Shorten([FromBody] GenerateShortCodeCommand command)
{
return Json(MediatR.Send(command));
}
public async Task<IActionResult> Shorten([FromBody] GenerateShortCodeCommand command,CancellationToken cancellationToken=default)
=>Ok(await MediatR.Send(command, cancellationToken));
}
8 changes: 3 additions & 5 deletions src/SwiftLink.Shared/Result.cs
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
using System.Text.Json.Serialization;

namespace SwiftLink.Shared;
namespace SwiftLink.Shared;

public class Result
{
public bool IsSuccess { get; init; }

[JsonIgnore]
public bool IsFailure => !IsSuccess;
public bool IsFailure
=> !IsSuccess;

public string Message { get; init; }

Expand Down

0 comments on commit 2307fae

Please sign in to comment.