如何在NHibernate 3.2中实现通用仓储模式和UoW

4

我新接触NHibernate,正试图在ASP.NET MVC 3应用程序中实现通用仓储模式工作单元。我谷歌了这个主题并找到了一些链接,但它们对我来说都过于复杂。我使用StructureMap作为我的IOC。你能推荐给我一些链接或博客文章吗?


1
NHibernate的ISession已经代表了工作单元和对存储库的访问。 - Andre Loker
一个仓储应该封装数据访问层,也就是说它会使用但不会暴露Nhibernate。而且一个经过适当设计的仓储(对于你的需求来说,通用仓储是无用的)也不需要工作单元。 - MikeSW
2个回答

5
以下是需要阅读的内容:

以下是需要阅读的内容:

我在最近的项目中使用的实现看起来像:

public interface IRepository<T>
{
    IEnumerable<T> GetAll();
    T GetByID(int id);
    T GetByID(Guid key);
    void Save(T entity);
    void Delete(T entity);
}

public class Repository<T> : IRepository<T>
{
    protected readonly ISession Session;

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

    public IEnumerable<T> GetAll()
    {
        return Session.Query<T>();
    }

    public T GetByID(int id)
    {
        return Session.Get<T>(id);
    }

    public T GetByID(Guid key)
    {
        return Session.Get<T>(key);
    }

    public void Save(T entity)
    {
        Session.Save(entity);
        Session.Flush();
    }

    public void Delete(T entity)
    {
        Session.Delete(entity);
        Session.Flush();
    }
}

谢谢,我明白了。但现在,我该如何通过注入创建一个ISession对象呢?我的构造函数是public Repository(ISession session),但似乎只能通过OpenSession方法来创建ISession对象;例如,如何通过StructureMap使用这个仓储?能否再详细解释一下? - amiry jd
1
@king.net 我个人更喜欢使用Ninject而不是Structure Map,但是类似的概念同样适用。在Ninject中,我会这样做:Bind<ISession>().ToMethod(x => NHibernateHelper.OpenSession()).InRequestScope(); - Jesse

1

看看这个解决方案 - https://bitbucket.org/cedricy/cygnus/overview

这是一个简单的仓储模式实现,我们在生产 MVC 1、2 和 3 应用程序中使用过。

当然,自那时以来,我们已经学到了直接针对 ISession 运行查询的好处。这样可以更好地控制它们。而且Ayende 告诉我们不要这样做。

谢谢 Cedric!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接