I am experimenting with something and below are details:
I have implemented domain classes with IValidatableObject, so domain can validate itself. This I guess is good practice, to ensure object is valid before it's committed to persistent state, including any dependent entity required.
What I wanted to do was create a common Repository with generic implementation, code below:
public class Repository<T> : IRepository<T> where T : IValidatableObject
{
public int Save(T obj)
{
var validationResult = obj.Validate(new ValidationContext(this, null, null)).ToList();
if (validationResult.Any())
{
var inner = new StringBuilder();
foreach (var result in validationResult)
{
inner.Append(result.ErrorMessage + $"\n\r");
}
throw new ValidationException("Not all validation rules passed, please see inner exception for more detail", new Exception(inner.ToString()));
}
//if we reach here then, all validations have passed
return 0;
}
}
This IRepository is not implemented by any other domain classes and business layer is yet to be built.
What I want to do is when Save(T obj) is called it should run validation on the "obj".
Is this right way to do it?
I wanted to have this way so, tomorrow, implementation can be changed easily via DI.
Also, business classes have to initialise IRepository (DI), which means only change that comes is in business layer and nowhere else.
Aucun commentaire:
Enregistrer un commentaire