My project is composed of several parts: Repositories, Services, Domain objects, etc in a .NET MVC web application.
My repositories handle all data i/o, the services are responsible for CRUD operations as well as other logic, such as getting a count of objects from the database.
I am trying to shift from an "anemic" domain model where my domain objects are simply classes with properties to having more business logic where it belongs. In this case, I would like to have the domain object handle the logic where it checks the database for duplicates, but I also don't want to have the code that communicates with the repository inside of the domain object (I read it is bad practice to have an object responsible for persistence with the database, so I'm assuming this is the same thing.)
I don't particularly like this solution, as it just doesn't feel good, and I'd like to get a better handle on how to handle these sorts of situations. Can anybody give me some advice here?
public interface IDuplicateChecker<T> where T : class
{
bool IsDuplicate(T t);
}
public class DuplicateDocumentChecker : IDuplicateChecker<Document>
{
public bool IsDuplicate(Document doc)
{
IDocumentService documentService = new DocumentService();
// simplified check -- really there are a few other properties to match
if (documentService.Count(doc.DocumentNumber) > 0)
{
return true;
}
return false;
}
}
public class Document
{
public Document(string documentNumber)
{
// validation and other removed for brevity
DocumentNumber = documentNumber;
}
// simplified document properties for brevity
public string DocumentNumber { get; set; }
public bool IsDuplicate { get; set; }
public void CheckForDuplicates(IDuplicateChecker<Document> checker)
{
IsDuplicate = checker.IsDuplicate(this);
}
}