Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add SaveEntitiesAsync to get and raise all events #51

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,8 @@ public async Task<MakeCommentCommandResponse> Handle(MakeCommentCommand request,
comment.RaiseMakeCommentEvent();

await _commentRepository.CreateAsync(comment, cancellationToken);
await _commentRepository.SaveChangesAsync(cancellationToken);

await _commentRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken);



Expand Down
13 changes: 13 additions & 0 deletions src/Blogger.BuildingBlocks/Domain/IRepository.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Blogger.BuildingBlocks.Domain
{
public interface IRepository<T> where T : IAggregateRoot
{
IUnitOfWork UnitOfWork { get; }
}
}
13 changes: 13 additions & 0 deletions src/Blogger.BuildingBlocks/Domain/IUnitOfWork.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Blogger.BuildingBlocks.Domain
{
public interface IUnitOfWork: IDisposable
{
Task<bool> SaveEntitiesAsync(CancellationToken cancellationToken = default);
}
}
2 changes: 1 addition & 1 deletion src/Blogger.Domain/ArticleAggregate/IArticleRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

namespace Blogger.Domain.ArticleAggregate;

public interface IArticleRepository
public interface IArticleRepository:IRepository<Article>
{
Task<bool> HasIdAsync(ArticleId articleId, CancellationToken cancellationToken);

Expand Down
2 changes: 1 addition & 1 deletion src/Blogger.Domain/CommentAggregate/ICommentRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
using Blogger.Domain.ArticleAggregate;

namespace Blogger.Domain.CommentAggregate;
public interface ICommentRepository
public interface ICommentRepository:IRepository<Comment>
{
Task<Comment?> GetCommentByApproveLinkAsync(string link, CancellationToken cancellationToken);
Task<IReadOnlyCollection<Comment>> GetApprovedArticleCommentsAsync(ArticleId articleId, CancellationToken cancellationToken);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@

namespace Blogger.Domain.SubscriberAggregate;

public interface ISubscriberRepository
public interface ISubscriberRepository:IRepository<Subscriber>
{
Task CreateAsync(Subscriber subscriber, CancellationToken cancellationToken);
Task<Subscriber?> FindByIdAsync(SubscriberId subscriberId);
Expand Down
7 changes: 7 additions & 0 deletions src/Blogger.Infrastructure/DependencyInjection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,13 @@ public static IServiceCollection ConfigureInfrastructureLayer(this IServiceColle
{
services.Configure<EmailSettings>(configuration.GetSection(nameof(EmailSettings)));

var application = typeof(IAssemblyMarker);

services.AddMediatR(configure =>
{
configure.RegisterServicesFromAssembly(application.Assembly);
});

services.AddDbContext<BloggerDbContext>(options =>
{
options.UseSqlServer(configuration.GetConnectionString(BloggerDbContextSchema.DefaultConnectionStringName));
Expand Down
53 changes: 45 additions & 8 deletions src/Blogger.Infrastructure/Persistence/BloggerDbContext.cs
Original file line number Diff line number Diff line change
@@ -1,26 +1,63 @@
using Blogger.Domain.ArticleAggregate;
using Blogger.Domain.CommentAggregate;
using Blogger.Domain.SubscriberAggregate;
using Microsoft.EntityFrameworkCore;

using System.Data;
using Blogger.BuildingBlocks.Domain;
using MediatR;
using Microsoft.EntityFrameworkCore.Storage;

namespace Blogger.Infrastructure.Persistence;
public class BloggerDbContext : DbContext
public class BloggerDbContext : DbContext, IUnitOfWork
{
private readonly IMediator? _mediator;
private IDbContextTransaction? _currentTransaction;

public BloggerDbContext(DbContextOptions<BloggerDbContext> dbContextOptions)
: base(dbContextOptions)
: base(dbContextOptions) { }

public BloggerDbContext(DbContextOptions<BloggerDbContext> dbContextOptions, IMediator mediator/*, IDbContextTransaction dbContextTransaction*/) : base(dbContextOptions)
{

_mediator = mediator ?? throw new ArgumentNullException(nameof(mediator));

}

public IDbContextTransaction GetCurrentTransaction() => _currentTransaction!;
public bool HasActiveTransaction => _currentTransaction != null;

public DbSet<Article> Articles => Set<Article>();
public DbSet<Comment> Comments => Set<Comment>();
public DbSet<Subscriber> Subscribers => Set<Subscriber>();

public async Task<bool> SaveEntitiesAsync(CancellationToken cancellationToken = default)
{
await _mediator!.DispatcherEventAsync(this);
await base.SaveChangesAsync(cancellationToken);
return true;
}

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseSqlServer("data source=.;initial catalog=HealthDB;TrustServerCertificate=True;Trusted_Connection=True;");
}

base.OnConfiguring(optionsBuilder);

}

public async Task<IDbContextTransaction?> BeginTransactionAsync()
{
if (_currentTransaction != null) return null;

_currentTransaction = await Database.BeginTransactionAsync(IsolationLevel.ReadCommitted);

return _currentTransaction;
}

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.HasDefaultSchema(BloggerDbContextSchema.DefaultSchema);

var infrastructureAssembly = typeof(IAssemblyMarker).Assembly;
modelBuilder.ApplyConfigurationsFromAssembly(infrastructureAssembly);
modelBuilder.ApplyConfigurationsFromAssembly(infrastructureAssembly);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,15 @@
namespace Blogger.Infrastructure.Persistence;
public class BloggerDbContextFactory : IDesignTimeDbContextFactory<BloggerDbContext>
{
public BloggerDbContext CreateDbContext(string[] args)
public BloggerDbContextFactory(IServiceProvider serviceProvider)
{
var optionBuilder = new DbContextOptionsBuilder<BloggerDbContext>();
optionBuilder.UseSqlServer("data source=.;initial catalog=thisisnabi.blogger;TrustServerCertificate=True;Trusted_Connection=True;");
ServiceProvider = serviceProvider;
}

public IServiceProvider ServiceProvider { get; }

return new BloggerDbContext(optionBuilder.Options);
public BloggerDbContext CreateDbContext(string[] args)
{
return ServiceProvider.GetRequiredService<BloggerDbContext>();
}
}
28 changes: 28 additions & 0 deletions src/Blogger.Infrastructure/Persistence/MediatorExtension.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@


using System.Security.Cryptography;

using Blogger.BuildingBlocks.Domain;
using MediatR;

namespace Blogger.Infrastructure.Persistence;

public static class MediatorExtension
{
public static async Task DispatcherEventAsync(this IMediator mediator, BloggerDbContext bloggerDbContext)
{
var domainEntities = bloggerDbContext.ChangeTracker
.Entries<AggregateRoot<string>>()
.Where(x => x.Entity.Events != null && x.Entity.Events.Count != 0);

var domainEvents = domainEntities
.SelectMany(x => x.Entity.Events)
.ToList();

domainEntities.ToList()
.ForEach(entity => entity.Entity.ClearEvents());

foreach (var domainEvent in domainEvents)
await mediator.Publish(domainEvent);
}
}
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
using System.Linq;

using Blogger.BuildingBlocks.Domain;
using Blogger.Domain.ArticleAggregate.Models;

namespace Blogger.Infrastructure.Persistence.Repositories;

public class ArticleRepository(BloggerDbContext bloggerDbContext) : IArticleRepository
{
public IUnitOfWork UnitOfWork => bloggerDbContext;

public Task<bool> HasIdAsync(ArticleId articleId, CancellationToken cancellationToken) =>
bloggerDbContext.Articles.AnyAsync(x => x.Id == articleId, cancellationToken);

Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
 namespace Blogger.Infrastructure.Persistence.Repositories;
using Blogger.BuildingBlocks.Domain;

namespace Blogger.Infrastructure.Persistence.Repositories;

public class CommentRepository(BloggerDbContext bloggerDbContext) : ICommentRepository
{
public IUnitOfWork UnitOfWork => bloggerDbContext;

public Task<Comment?> GetCommentByApproveLinkAsync(string link, CancellationToken cancellationToken)
{
return bloggerDbContext.Comments.FirstOrDefaultAsync(x => x.ApproveLink.ApproveId == link, cancellationToken);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
namespace Blogger.Infrastructure.Persistence.Repositories;
using Blogger.BuildingBlocks.Domain;

namespace Blogger.Infrastructure.Persistence.Repositories;
public class SubscriberRepository(BloggerDbContext bloggerDbContext) : ISubscriberRepository
{

public IUnitOfWork UnitOfWork => bloggerDbContext;
public async Task CreateAsync(Subscriber subscriber, CancellationToken cancellationToken)
{
await bloggerDbContext.Subscribers.AddAsync(subscriber, cancellationToken);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,21 @@
using Blogger.Infrastructure.Persistence;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;


namespace Blogger.IntegrationTests.Fixtures;

public class BloggerDbContextFixture : EfDatabaseBaseFixture<BloggerDbContext>
{
public BloggerDbContextFixture(IServiceProvider serviceProvider)
{
ServiceProvider = serviceProvider;
}

public IServiceProvider ServiceProvider { get; }

protected override BloggerDbContext BuildDbContext(DbContextOptions<BloggerDbContext> options)
{
return new BloggerDbContext(options);
return ServiceProvider.GetRequiredService<BloggerDbContext>();
}
}