开发者

How do you implement a 3 layer model with NHibernate?

Taking the traditional 3 layer approach (not necessarily 3 tiers):

UI BLL DAL

How does NHibernate fit? In most cases I see people allowing NHibernate to directly populate domain objects/entities, which obviously requires a reference from 开发者_StackOverflow社区NHibernate to these entities. If domain entities are part of the BLL, this seems to require a reference from the DAL (where NHibernate resides) to the BLL (where domain objects reside).

Doesn't this go against the typical thinking of separating each layer, with each layer only being dependent on the one below it? What am I missing here?


I can give you an example, how I generally layer with NHibernate for a n-tier architecture:

Data Access Layer

  • NHibernate SessionFactory
  • Mappings with FluentNHibernate

Example for a mapping:

public class CategoryMap : ClassMap<Domain.Entities.Category>
{
    public CategoryMap()
    {
        ...
    }
}

Business Layer

  • Repositories : BaseRepository

Example for a repository:

public class CategoryRepository : BaseRepository<Domain.Entities.Category>,
    Domain.DataInterfaces.Business.Repositories.ICategoryRepository
{
    public CategoryRepository(ISession session)
        : base(session)
    {
    }
}
  • BaseRepository (CRUD, GetById, GetAll)

Example for a base repository:

public class BaseRepository<T> : IBaseRepository<T>
{
    public ISession Session { get; set; }

    public BaseRepository(ISession session)
    {
        Session = session;
    }
 }

Domain Layer

  • DataInterfaces (IRepository, IBaseRepository)
  • Entities : BaseEntity
  • Persistance (IEntity, IBaseEnity)

So, the only layer which is referencing NHibernate is actually the data layer and the business (NHibernate.ISession). The domain layer is shared between all layers and does not know about NHibernate. For simplicy you could merge the business and data layer into one layer. I generally tend to seperate them, but it depends on the project size.

How do you implement a 3 layer model with NHibernate?

If you really want seperation, I also suggest you to have a look at dependency injection to reduce the dependencies between different layers.

Hope that helps you.


NHibernate is most suitable for a different architecture (still layered, but not stacked the same way).

The presentation layer uses NHibernate as a Data Mapper (and Unit of Work) to decouple its Domain Model (that is, its business logic) from persistence concerns.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜