开发者

What types of code are appropriate for the service layer?

Assume you have entities, a service layer, and repositories (with an ORM like NHibernate). The UIs interact with the service layer.

What types of code are appropriate for the service layer?


Repository Coordination?

It looks like entities should not reference the repository so should calls for loading/saving/evicting entities exist in the service layer?

Business Logic that Involves Repositories?

If the above is true, should something like checking if a username is distinct go in the service layer (i.e. call GetUsersByUsername and check the results)? Before suggesting that the DB should handle distinct, what about verifying that a password hasn't been used in 90 days?

Business Logic that Involves Multiple Entities?

I'm not sure about this one, but say you have the need to apply an operation against a collection of entities t开发者_运维知识库hat may or may not be related and is not really applicable to a single entity. Should entities be capable of operating on these collections or does this sort of thing belong in the service layer?

Mapping?

Whether you use DTOs or send your entities to/from your service layer, you will likely end up mapping (preferably with AutoMapper). Does this belong in the service layer?


I'm looking for confirmation (or rejection) of the ideas listed above as well as any other thoughts about the responsibilities of a service layer when working with entities/repositories.


Repository Coordination?

Aggregate roots should draw transactional boundaries. Therefore - multiple repositories should rarely be involved. If they are - that usually happens when You are creating new aggregate root (as opposed to modifying its state).


Business Logic that Involves Repositories?

Yes, checking if username is distinct might live in service layer. Because User usually is an aggregate root and aggregate roots live in global context (there is nothing that "holds" them). I personally put that kind of logic in repository or just check directly through ORM.

As for checking password usage - that's a concern of user itself and should live underneath User object. Something like this:

class User{
  void Login(){
    LoggedOn=DateTime.Now;
    ...
  }
  bool HasLoggedInLast90Days(){
    return (DateTime.Now-LoggedOn).Days<=90;
  }
}

Business Logic that Involves Multiple Entities?

Aggregate root should manage their entity collections.

class Customer{
  void OrderProduct(Product product){
    Orders.Add(new Order(product)); //<--
  }
}

But remember that aggregate root should not micro-control its entities.

E.g. this is bad:

class Customer{
  void IsOrderOverdue(Order order){
    return Orders.First(o=>o==order)....==...;
  }
}

Instead use:

class Order{
  void IsOverdue(){
    return ...;
  }
}

Mapping?

I suppose mapping to dto`s live in service layer. My mapping classes lives next to view model classes in web project.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜