Home

Castle Stronghold

Using it

To use the NHibernate facility you just need to register it and provide the configuration. If you want to use the integration level 2 approach, you can make your data access component require the ISessionManager.

ISessionManager

The following code exemplifies a common data access component:


public class BlogDao
{
    private ISessionManager sessionManager;

    public BlogDao(ISessionManager sessionManager)
    {
        this.sessionManager = sessionManager;
    }

    public Blog CreateBlog(String name)
    {
        using(ISession session = sessionManager.OpenSession())
        {
            Blog blog = new Blog();
            blog.Name = name;

            session.Save(blog);

            return blog;
        }
    }
}

When OpenSession is called without arguments, the first configured Session Factory is used. If you have more than one database you have to specify the alias:


public Blog CreateBlog(String name)
{
    using(ISession session = sessionManager.OpenSession("oracle2"))
    {
        Blog blog = new Blog();
        blog.Name = name;

        session.Save(blog);

        return blog;
    }
}

If you component access another component, or just call another method that will use a session, within an opened session, the SessionManager will use the same session. For example:


public class BlogDao
{
    private ISessionManager sessionManager;

    public BlogDao(ISessionManager sessionManager)
    {
        this.sessionManager = sessionManager;
    }

    public Blog CreateBlog(String name)
    {
        using(ISession session = sessionManager.OpenSession())
        {
            // make sure there are not blogs with this name
            
            Blog existing = FindByName(name);
            
            if (existing != null)
            {
                throw new DaoLayerException("Duplicated blog name");
            }
        
            Blog blog = new Blog();
            blog.Name = name;

            session.Save(blog);

            return blog;
        }
    }
    
    public Blog FindByName(String name)
    {
        // If the previous call had opened a session
        // this one will reuse it
        using(ISession session = sessionManager.OpenSession())
        {
            ...
        }
    }
    
}
Google
Search WWW Search castleproject.org