Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
8e78e3d
feat(EntityFramework): Support EntityFrameWork
zhenlei520 Apr 29, 2022
ccc9b16
Merge branch 'main' of https://github.com/masastack/MASA.Contrib into…
zhenlei520 Apr 29, 2022
571f8a4
refactor(Data): Refactoring soft delete related functions
zhenlei520 May 7, 2022
cee56bc
Merge branch 'main' of https://github.com/masastack/MASA.Contrib into…
zhenlei520 May 7, 2022
9dc9f05
refactor(SoftDelete): Refactor soft delete
zhenlei520 May 9, 2022
39e68ec
test(EntityFramework): Refactor EntityFramework UnitTest
zhenlei520 May 9, 2022
320fd97
chore: Change .editorconfig
zhenlei520 May 9, 2022
334b11a
chore: format code
zhenlei520 May 9, 2022
e00505b
docs(EntityFrameworkCore): Adjust filter documentation
zhenlei520 May 9, 2022
dd6817d
chore: Adjust Global Using
zhenlei520 May 9, 2022
3f187cb
Update .editorconfig
zhenlei520 May 9, 2022
4d835be
feat(Ddd): Support Domain Event By AggregateRoot
zhenlei520 May 10, 2022
1bfe5f2
test(DomainEvent): Add DomainEvent By AggregateRoot
zhenlei520 May 10, 2022
7d76714
chore: Modify the Domain document
zhenlei520 May 10, 2022
02399a1
chore: Fix unit tests, add comments
zhenlei520 May 10, 2022
1051c52
Merge branch 'main' of https://github.com/masastack/MASA.Contrib into…
zhenlei520 May 10, 2022
0b54b1c
chore: Remove wrong project path
zhenlei520 May 10, 2022
13a3484
chore: Add Masa.Contrib.Data.EntityFramework Library
zhenlei520 May 10, 2022
c8a5fe9
chore(EntityFramework): Modify IGenerateDomainEvents to IGenerateDoma…
zhenlei520 May 11, 2022
0a059d0
chore: Change Masa.Contribs.Ddd.Domain.Entities.Tests To Masa.Contrib…
zhenlei520 May 11, 2022
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
228 changes: 120 additions & 108 deletions Masa.Contrib.sln

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion src/BuildingBlocks/MASA.BuildingBlocks
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
<ProjectReference Include="..\..\BuildingBlocks\MASA.BuildingBlocks\src\Configuration\Masa.BuildingBlocks.Configuration\Masa.BuildingBlocks.Configuration.csproj" />
<ProjectReference Include="..\..\BuildingBlocks\MASA.BuildingBlocks\src\Data\Masa.BuildingBlocks.Data.Contracts\Masa.BuildingBlocks.Data.Contracts.csproj" />
<ProjectReference Include="..\..\BuildingBlocks\MASA.BuildingBlocks\src\Data\Masa.BuildingBlocks.Data\Masa.BuildingBlocks.Data.csproj" />
<ProjectReference Include="..\..\BuildingBlocks\MASA.BuildingBlocks\src\Ddd\Masa.BuildingBlocks.Ddd.Domain\Masa.BuildingBlocks.Ddd.Domain.csproj" />
</ItemGroup>

</Project>
26 changes: 24 additions & 2 deletions src/Data/Masa.Contrib.Data.EntityFrameworkCore/MasaDbContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ namespace Masa.Contrib.Data.EntityFrameworkCore;
public abstract class MasaDbContext : DbContext, IMasaDbContext
{
protected readonly IDataFilter? DataFilter;
protected readonly MasaDbContextOptions? Options;
protected readonly MasaDbContextOptions Options;
protected IDomainEventBus? DomainEventBus => Options.ServiceProvider.GetService<IDomainEventBus>();

public MasaDbContext(MasaDbContextOptions options) : base(options)
{
Expand Down Expand Up @@ -108,12 +109,33 @@ protected virtual void OnBeforeSaveChanges()
}
catch (Exception ex)
{
throw new Exception("An error occured when intercept SaveChanges() or SaveChangesAsync()()", ex);
throw new Exception("An error occured when intercept SaveChanges() or SaveChangesAsync()", ex);
}
}
DomainEventEnqueueAsync(ChangeTracker).ConfigureAwait(false).GetAwaiter().GetResult();
}
}

protected virtual async Task DomainEventEnqueueAsync(ChangeTracker changeTracker)
{
if (DomainEventBus == null)
return;

var domainEntities = changeTracker
.Entries<IGenerateDomainEvents>()
.Where(entry => entry.Entity.GetDomainEvents().Any());

var domainEvents = domainEntities
.SelectMany(entry => entry.Entity.GetDomainEvents())
.ToList();

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

foreach (var domainEvent in domainEvents)
await DomainEventBus.Enqueue(domainEvent);
}

/// <summary>
/// Automatic soft delete.
/// <inheritdoc/>
Expand Down
2 changes: 2 additions & 0 deletions src/Data/Masa.Contrib.Data.EntityFrameworkCore/_Imports.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
global using Masa.BuildingBlocks.Data;
global using Masa.BuildingBlocks.Data.Contracts.DataFiltering;
global using Masa.BuildingBlocks.Data.Options;
global using Masa.BuildingBlocks.Ddd.Domain.Entities;
global using Masa.BuildingBlocks.Ddd.Domain.Events;
global using Masa.Contrib.Data.EntityFrameworkCore.Filters;
global using Microsoft.EntityFrameworkCore;
global using Microsoft.EntityFrameworkCore.ChangeTracking;
Expand Down
4 changes: 4 additions & 0 deletions src/Data/Masa.Contrib.Data.UoW.EF/UnitOfWork.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,10 @@ public async Task CommitAsync(CancellationToken cancellationToken = default)

await Context.Database.CommitTransactionAsync(cancellationToken);
CommitState = CommitState.Commited;

var domainEventBus = ServiceProvider.GetService<IDomainEventBus>();
if (domainEventBus != null)
await domainEventBus.PublishQueueAsync();
}

public async Task RollbackAsync(CancellationToken cancellationToken = default)
Expand Down
1 change: 1 addition & 0 deletions src/Data/Masa.Contrib.Data.UoW.EF/_Imports.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
global using Masa.BuildingBlocks.Data;
global using Masa.BuildingBlocks.Data.Options;
global using Masa.BuildingBlocks.Data.UoW;
global using Masa.BuildingBlocks.Ddd.Domain.Events;
global using Masa.BuildingBlocks.Dispatcher.Events;
global using Masa.Contrib.Data.EntityFrameworkCore;
global using Microsoft.EntityFrameworkCore;
Expand Down
21 changes: 21 additions & 0 deletions test/Masa.Contrib.Data.UoW.EF.Tests/TestUnitOfWork.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Copyright (c) MASA Stack All rights reserved.
// Licensed under the MIT License. See LICENSE.txt in the project root for license information.

using Masa.BuildingBlocks.Ddd.Domain.Events;
using Microsoft.Extensions.Options;

namespace Masa.Contrib.Data.UoW.EF.Tests;
Expand Down Expand Up @@ -299,5 +300,25 @@ public async Task TestGetConnectionStringAsyncReturnTest1()
Assert.IsTrue(await connectionStringProvider.GetConnectionStringAsync() == connectionString);
}

[TestMethod]
public async Task TestCommitReturnPublishQueueIsValid()
{
IServiceCollection services = new ServiceCollection();
Mock<IDomainEventBus> domainEventBus = new();
domainEventBus.Setup(eventBus => eventBus.PublishQueueAsync()).Verifiable();
services.AddScoped(serviceProvider => domainEventBus.Object);
Mock<IEventBusBuilder> eventBuilder = new();
eventBuilder.Setup(eb => eb.Services).Returns(services).Verifiable();
eventBuilder.Object.UseUoW<CustomDbContext>(options => options.UseTestSqlite($"Data Source=test_{Guid.NewGuid()}"));

var serviceProvider = services.BuildServiceProvider();
var dbContext = serviceProvider.GetRequiredService<CustomDbContext>();
dbContext.Database.EnsureCreated();
var unitOfWork = new UnitOfWork<CustomDbContext>(serviceProvider);
var _ = unitOfWork.Transaction;
await unitOfWork.CommitAsync();
domainEventBus.Verify(eventBus => eventBus.PublishQueueAsync(), Times.Once());
}

private string GetDataBaseConnectionString(CustomDbContext dbContext) => dbContext.Database.GetConnectionString()!;
}
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
// Copyright (c) MASA Stack All rights reserved.
// Licensed under the MIT License. See LICENSE.txt in the project root for license information.

namespace Masa.Contribs.Ddd.Domain.Entities.Tests;
namespace Masa.Contrib.Ddd.Domain.Entities.Tests;

public class Users : AggregateRoot<Guid>
public class User : AggregateRoot<Guid>
{
public string Name { get; set; }
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
// Copyright (c) MASA Stack All rights reserved.
// Licensed under the MIT License. See LICENSE.txt in the project root for license information.

using Masa.Contrib.Ddd.Domain.Entities.Tests;

namespace Masa.Contrib.Ddd.Domain.Integrated.Tests;

public class CustomizeDbContext : MasaDbContext<CustomizeDbContext>
{
public DbSet<User> User { get; set; }

public CustomizeDbContext(MasaDbContextOptions<CustomizeDbContext> options) : base(options)
{
}
}
62 changes: 62 additions & 0 deletions test/Masa.Contrib.Ddd.Domain.Integrated.Tests/DomainEventTest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
// Copyright (c) MASA Stack All rights reserved.
// Licensed under the MIT License. See LICENSE.txt in the project root for license information.

using Masa.BuildingBlocks.Data;
using Masa.BuildingBlocks.Ddd.Domain.Events;
using Masa.Contrib.Ddd.Domain.Integrated.Tests.DomainEvents;
using System.Collections.Concurrent;
using System.Linq;
using System.Threading.Tasks;
using Masa.Contrib.Ddd.Domain.Entities.Tests;

namespace Masa.Contrib.Ddd.Domain.Integrated.Tests;

[TestClass]
public class DomainEventTest
{
private IServiceProvider _serviceProvider;

[TestInitialize]
public void Initialize()
{
IServiceCollection services = new ServiceCollection();
services.Configure<MasaDbConnectionOptions>(options =>
{
options.ConnectionStrings = new ConnectionStrings()
{
DefaultConnection = $"Data Source=test_{Guid.NewGuid()}"
};
});
services.AddDomainEventBus(dispatchOptions =>
{
dispatchOptions
.UseDaprEventBus<IntegrationEventLogService>(options => options.UseEventLog<CustomizeDbContext>())
.UseEventBus()
.UseUoW<CustomizeDbContext>(dbOptions => dbOptions.UseSqlite())
.UseRepository<CustomizeDbContext>();
});
_serviceProvider = services.BuildServiceProvider();
}

[TestMethod]
public async Task TestSaveChangesReturnDomainEventBus()
{
var dbContext = _serviceProvider.GetRequiredService<CustomizeDbContext>();
await dbContext.Database.EnsureCreatedAsync();
var user = new User()
{
Name = "Jim"
};
user.AddDomainEvent(new AddUserIntegrationDomainEvent()
{
Name = user.Name
});
await dbContext.Set<User>().AddAsync(user);
await dbContext.SaveChangesAsync();
var domainEventBus = _serviceProvider.GetRequiredService<IDomainEventBus>();
var fields = domainEventBus.GetType().GetFields(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic).ToList();
var field = fields.Where(field => field.Name == "_eventQueue").First();
var eventQueue = (ConcurrentQueue<IDomainEvent>)field.GetValue(domainEventBus)!;
Assert.IsTrue(eventQueue.Count == 1);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
// Copyright (c) MASA Stack All rights reserved.
// Licensed under the MIT License. See LICENSE.txt in the project root for license information.

namespace Masa.Contrib.Ddd.Domain.Integrated.Tests.DomainEvents;

public record AddUserIntegrationDomainEvent : IntegrationDomainEvent
{
public string Name { get; set; }

public override string Topic { get; set; } = nameof(AddUserIntegrationDomainEvent);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="coverlet.msbuild" Version="3.1.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.11.0" />
<PackageReference Include="MSTest.TestAdapter" Version="2.2.7" />
<PackageReference Include="MSTest.TestFramework" Version="2.2.7" />
<PackageReference Include="coverlet.collector" Version="3.0.2">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\..\src\Data\Masa.Contrib.Data.EntityFrameworkCore.Sqlite\Masa.Contrib.Data.EntityFrameworkCore.Sqlite.csproj" />
<ProjectReference Include="..\..\src\Data\Masa.Contrib.Data.UoW.EF\Masa.Contrib.Data.UoW.EF.csproj" />
<ProjectReference Include="..\..\src\Ddd\Masa.Contrib.Ddd.Domain.Repository.EF\Masa.Contrib.Ddd.Domain.Repository.EF.csproj" />
<ProjectReference Include="..\..\src\Ddd\Masa.Contrib.Ddd.Domain\Masa.Contrib.Ddd.Domain.csproj" />
<ProjectReference Include="..\..\src\Dispatcher\Masa.Contrib.Dispatcher.Events\Masa.Contrib.Dispatcher.Events.csproj" />
<ProjectReference Include="..\..\src\Dispatcher\Masa.Contrib.Dispatcher.IntegrationEvents.Dapr\Masa.Contrib.Dispatcher.IntegrationEvents.Dapr.csproj" />
<ProjectReference Include="..\..\src\Dispatcher\Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF\Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF.csproj" />
<ProjectReference Include="..\Masa.Contrib.Ddd.Domain.Entities.Tests\Masa.Contrib.Ddd.Domain.Entities.Tests.csproj" />
</ItemGroup>

</Project>
15 changes: 15 additions & 0 deletions test/Masa.Contrib.Ddd.Domain.Integrated.Tests/_Imports.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
// Copyright (c) MASA Stack All rights reserved.
// Licensed under the MIT License. See LICENSE.txt in the project root for license information.

global using Masa.Contrib.Data.EntityFrameworkCore;
global using Masa.Contrib.Data.EntityFrameworkCore.Sqlite;
global using Masa.Contrib.Data.UoW.EF;
global using Masa.Contrib.Ddd.Domain.Events;
global using Masa.Contrib.Ddd.Domain.Repository.EF;
global using Masa.Contrib.Dispatcher.Events;
global using Masa.Contrib.Dispatcher.IntegrationEvents.Dapr;
global using Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF;
global using Microsoft.EntityFrameworkCore;
global using Microsoft.Extensions.DependencyInjection;
global using Microsoft.VisualStudio.TestTools.UnitTesting;
global using System;
14 changes: 8 additions & 6 deletions test/Masa.Contrib.Ddd.Domain.Tests/DomainEventBusTest.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
// Copyright (c) MASA Stack All rights reserved.
// Licensed under the MIT License. See LICENSE.txt in the project root for license information.

using Masa.Contrib.Ddd.Domain.Entities.Tests;

namespace Masa.Contrib.Ddd.Domain.Tests;

[TestClass]
Expand Down Expand Up @@ -73,12 +75,12 @@ public async Task TestPublishDomainCommandAsync()
_eventBus.Setup(eventBus => eventBus.PublishAsync(It.IsAny<CreateProductDomainCommand>()))
.Callback<CreateProductDomainCommand>((domainEvent) =>
{
Mock<IRepository<Users>> userRepository = new();
var user = new Users()
Mock<IRepository<User>> userRepository = new();
var user = new User()
{
Name = "Jim"
};
userRepository.Setup(repository => repository.AddAsync(It.IsAny<Users>(), CancellationToken.None)).Verifiable();
userRepository.Setup(repository => repository.AddAsync(It.IsAny<User>(), CancellationToken.None)).Verifiable();
domainEvent.UnitOfWork!.CommitAsync();
});

Expand Down Expand Up @@ -158,7 +160,7 @@ public void TestNotRepository()

Assert.ThrowsException<NotImplementedException>(() =>
{
services.AddDomainEventBus(new Assembly[1] { typeof(Users).Assembly });
services.AddDomainEventBus(new Assembly[1] { typeof(User).Assembly });
});
}

Expand All @@ -176,9 +178,9 @@ public void TestUserRepository()
var integrationEventBus = new Mock<IIntegrationEventBus>();
services.AddScoped(_ => integrationEventBus.Object);

Mock<IRepository<Users>> repository = new();
Mock<IRepository<User>> repository = new();
services.AddScoped(_ => repository.Object);
services.AddDomainEventBus(new[] { typeof(Users).Assembly, typeof(DomainEventBusTest).Assembly });
services.AddDomainEventBus(new[] { typeof(User).Assembly, typeof(DomainEventBusTest).Assembly });
}

[TestMethod]
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
// Copyright (c) MASA Stack All rights reserved.
// Licensed under the MIT License. See LICENSE.txt in the project root for license information.

namespace Masa.Contrib.Ddd.Domain.Tests.Events;

public record AddUserIntegrationDomainEvent : IntegrationDomainEvent
{
public string Name { get; set; }

public override string Topic { get; set; } = nameof(AddUserIntegrationDomainEvent);
}
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
<ItemGroup>
<ProjectReference Include="..\..\src\Ddd\Masa.Contrib.Ddd.Domain\Masa.Contrib.Ddd.Domain.csproj" />
<ProjectReference Include="..\..\src\Dispatcher\Masa.Contrib.Dispatcher.Events\Masa.Contrib.Dispatcher.Events.csproj" />
<ProjectReference Include="..\Masa.Contribs.Ddd.Domain.Entities.Tests\Masa.Contribs.Ddd.Domain.Entities.Tests.csproj" />
<ProjectReference Include="..\Masa.Contrib.Ddd.Domain.Entities.Tests\Masa.Contrib.Ddd.Domain.Entities.Tests.csproj" />
</ItemGroup>

</Project>
1 change: 0 additions & 1 deletion test/Masa.Contrib.Ddd.Domain.Tests/_Imports.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
global using Masa.Contrib.Ddd.Domain.Events;
global using Masa.Contrib.Ddd.Domain.Tests.Events;
global using Masa.Contrib.Ddd.Domain.Tests.Services;
global using Masa.Contribs.Ddd.Domain.Entities.Tests;
global using Microsoft.Extensions.DependencyInjection;
global using Microsoft.Extensions.Options;
global using Microsoft.VisualStudio.TestTools.UnitTesting;
Expand Down