Mantisimo
Mantisimo

Reputation: 4283

DDD Enity persistance scenario

I'm trying to workout the best place to persist my domain changes. I've the following entities:

public class Period
{
   public Guid PeriodId { get; set; }
   public DateTime StartDate { get; set; }
   public DateTime EndDate { get; set; }
}

Trade
{
   public Guid TradeId { get; set; }
   Trader Instigator { get; set; }
   Trader Acceptor { get; set; }
   Period period { get; set; }
   public long Volume { get; set; }
   public decimal Price { get; set; }
}

Now for creating a new trade I've offloaded this to a Domain service

tradeService.PlaceTrade(Guid periodId, Guid UserId, decimal price. long volume)

The place trade functionality seems to fit nicely into the above domain service, the trade service persists the trade. I pass in an ITradeRepository class to facilitate.

To accept the trade I would like to have the following so that the domain logic for trade sits within the trade entity.

Trade trade = tradeRepository.Get(Guid tradeId)

TradeStatus = trade.Accept(userId);

The problem with the above is that the Trade entity is responsible for persisting the data and as such has a dependency to the ITradeRepository.

Is this the correct way of doing this? It feels dirty? Or work a better way be to create an extension method for the trade class to facilitate the same functionality for accepting a trade?

Any thoughts? Thanks

Upvotes: 2

Views: 135

Answers (2)

David Masters
David Masters

Reputation: 8295

As Jack Hughes says, the entities shouldn't have a dependency on their repositories. Also, I don't see why you need a 'Service' to get your trade entity? This is the responsibility of repositories. Also not sure why you would pass a reference to the trade object to the get method?

This is how I'd code it:

   //This is an application service method    
    public void AcceptTrade(Guid tradeId, Guid acceptingTraderId)
    {
        using (IUnitOfWork unitOfWork = UnitOfWorkFactory.Create())
        {
            Trade trade = _tradeRepository.GetById(tradeId);
            Trader acceptingTrader = _traderRepository.GetById(acceptingTraderId);

            trade.Accept(acceptingTrader);

            _tradeRepository.Save(trade);
        }
    }

Upvotes: 3

Jack Hughes
Jack Hughes

Reputation: 5654

The entities shouldn't know anything about the repositories. So the trade should accept the user id and set up its internal state to reflect it. But then the service or controller should then either add or save the trade to the repository. Saving the trade to the repository then persists the entity (and possibly many sub-entities that trade aggregates) in one go.

Upvotes: 3

Related Questions