Вопрос

I'm developing an application using domain driven design. One of the patterns I've been using is Repository pattern. For the sake of simplicity, let's say I have following classes and interfaces.

Car - domain class representing car domain concept.

public class Car {
  public int Id {get;private set;}
  public string SomeUniqueCode {get;private set;}
}

ICarRepository - interface for adding, deleting or saving changes to Car objects.

public interface ICarRepository{
  Car  AddCar(Car c);
  void DeleteCar(Car c);
}

My problem is, how to check uniqueness of SomeUniqueCode property among all Car objects in the database? That property is changed by user (not auto-generated) at any time during the object life-cycle. Of course, one solution would be to put the unique key in the database, but that is not the principle of DDD. I've seen Specification pattern used to validate single objects. How would that pattern be applied to a set of Car objects?

Is it legitimate that Specification class (let's call it CheckUniqueCarSpecification) accesses ICarRepository?

Это было полезно?

Решение

A repository mimics an in-memory collection. What I have used before is a Contains method as opposed to a Find method, I guess you could have either. A query layer could also be used for this. Just as you have a CarRepository you could have a CarQuery. Trying to check for uniqueness in the domain is somewhat pesky. I would do a check for the sake of convenience but still rely on the DB to raise the exception since you should also handle that case. Using the specification pattern for this may be more effort than it is worth.

Since repository is a 'collection' I wouldn't have Commit and Rollback on there.

Другие советы

Use DomainService ICarCodesLibrary.

public class Car {
  ctor(string someUniqueCode, ICarCodesLibrary codes)
  {
    // the check
    codes.IsValidCode(someUniqueCode)
  }
  public int Id {get;private set;}
  public string SomeUniqueCode {get;private set;}
}

Implement the interface in the place where u create the Car object and inject it. Also get rid of the properties and use fields. The ID is OK to be a prop.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top