MongoDB¶
To use MongoDB
database integration, the NuGet package CrystalSharp.MongoDb
must be installed.
IMPORTANT
Kindly keep in mind that this particular configuration is intended for the purpose of storing data in the database and reading the data from the database. However, the configuration procedures for the Event Store, Read Model Store, and Sagas will be approached differently.
In order to integrate a database effectively, it is necessary to adhere to the following mandatory steps:
- An aggregate must be inherited from
AggregateRoot<string>
. It is mandatory that the<string>
type be passed to the base class. - Override the property
public virtual TKey Id { get; protected set; }
. - Register the implementation of
MongoDB
. - Use
IMongoDbContext
forSaveChanges
,Find
andQuery
operations.
Following is the code that illustrates how to perform the above steps:
public class Order : AggregateRoot<string>
{
public override string Id { get; protected set; } = Guid.NewGuid().ToString("N");
public string OrderCode { get; private set; }
public decimal TotalPrice { get; private set; }
// Rest of the code and logic
}
In the above code snippet, Order
aggregate is inherited to AggregateRoot<string>
. Here, the Id
is of type string, which is why <string>
is passed to the base class. It is essential to pay attention to the overridden property Id
. Overriding the Id
property is mandatory, and its type must be string, as the Crystal Sharp framework specifically uses the string
type for the Id
in MongoDB
.
NOTE
If there are any domain event handlers, then those domain event handlers will be triggered only after the data has been successfully stored in the database.
Registration for the MongoDB
is required. Following is the code that illustrates how to register MongoDB
in the Program.cs
file:
MongoDbSettings mongoDbSettings = new("CONNECTION-STRING", "DATABASE-NAME");
CrystalSharpAdapter.New(builder.Services)
.AddCqrs(typeof(PlaceOrderCommandHandler))
.AddMongoDb(mongoDbSettings)
.CreateResolver();
In the above code snippet, when initializing the Crystal Sharp framework, the MongoDbSettings
class is instantiated with a connection string and the database name, and then a call to an extension method is made AddMongoDb(mongoDbSettings)
.
IMPORTANT
It is mandatory to use “IMongoDbContext” for performing “SaveChanges”, “Find” and “Query” operations.
IMongoDbContext
provides the following methods:
Task SaveChanges<TDocument>(TDocument document, CancellationToken cancellationToken = default) where TDocument : IAggregateRoot<string> |
Task |
IQueryable<TDocument> Query<TDocument>(Expression<Func<TDocument, bool>> expression) where TDocument : IAggregateRoot<string> |
Following is the code that illustrates the saving of data:
public class PlaceOrderCommandHandler : CommandHandler<PlaceOrderCommand, PlaceOrderResponse>
{
private readonly IMongoDbContext _dbContext;
public PlaceOrderCommandHandler(IMongoDbContext dbContext)
{
_dbContext = dbContext;
}
public override async Task<CommandExecutionResult<PlaceOrderResponse>> Handle(PlaceOrderCommand request, CancellationToken cancellationToken = default)
{
Order order = Order.PlaceOrder(request.OrderCode, request.TotalPrice);
await _dbContext.SaveChanges(order, cancellationToken).ConfigureAwait(false);
PlaceOrderResponse response = new() { OrderId = order.GlobalUId };
return await Ok(response);
}
}
In the above code snippet, IMongoDbContext
is injected into the command handler constructor, and then in the Handle
method of the command handler, a new order is created and saved.