I want ask experienced software developers and architects about this domain class which I found one day in some code.
public class User : Entity
{
public virtual string Firstname { get; set; }
public virtual string Lastname { get; set; }
public User(string firstName, string lastName, IUserRepository userRepository, IUserService userService)
{
Firstname = firstName;
Lastname = lastName
userRepository.Save(this);
userService.DoSomeStaff(this);
}
}
What you think about SOLID principles in particular regarding the constructor? I think that it breaks at least the single responsibility principle, because:
- the constructor initializes the object, and
- saves the object to the DB using a repository, and
- does some stuff using a service.
Maybe there is some project architecture that recommends this code style?
Here are the definitions for the involved repository and service:
public class UserRepository : IUserRepository
{
// some code of repository pattern with Nhibernate
public void Save(User user)
{
//here Session is Nhibernate.ISession
Session.SaveOrUpdate(user);
}
}
public class UserService : IUserService
{
private readonly ISomeName1Repository _someName1Repository;
private readonly ISomeName2Repository _someName2Repository;
public UserService(ISomeName1Repository someName1Repository, ISomeName2Repository someName2Repository)
{
_someName1Repository = someName1Repository;
_someName2Repository = someName2Repository;
}
public void DoSomeStaff(User user)
{
var foo = _someName1Repository.DoSomeStaff();
// some work here with user
}
}