public class Ticket
{
public int Id;
public TicketState State;
public Ticket()
{
// from where do I get the "New" state entity here? with its id and name
State = State.New;
}
public void Finished()
{
// from where do I get the "Finished" state entity here? with its id and name
State = State.Finished;
}
}
public class TicketState
{
public int Id;
public string Name;
}
类状态直接在领域对象ticket中使用。在票的生命周期后期,可能设置其他状态。
票据被持久化到Ticket表中,以及TicketState。因此,在数据库中,票将具有指向票状态表的外键。
当在实体中设置适当的状态时,如何从数据库加载状态实例?我需要将仓库注入到实体中吗?我需要使用像Castle这样的框架吗?还是有更好的解决方案,比如从外部传递状态?
public class Ticket
{
//...
public ITicketStateRepository stateRep; //<-- inject
public Ticket()
{
State = stateRep.GetById(NEW_STATE_ID);
}
//...
}
有没有最佳实践?到目前为止,我没有使用任何依赖注入框架或其他任何东西,并将任何持久性事物保留在我的领域之外。
另一种方法:
public class Ticket
{
//...
public Ticket(NewTicketState newTicketState)
{
State = newTicketState;
}
public void Finished(FinishedTicketState finishedTicketState)
{
State = finishedTicketState;
}
//...
}