开发者

ASP.NET MVC: run code after view has rendered (close db transaction)

开发者 https://www.devze.com 2022-12-24 23:56 出处:网络
I am using ASP.NET MVC2 with NHibernate, but am facing an issue. All calls to the database via NHibernate should be inside a transaction, however code inside the view kicks off database calls in some

I am using ASP.NET MVC2 with NHibernate, but am facing an issue. All calls to the database via NHibernate should be inside a transaction, however code inside the view kicks off database calls in some instances. Thus there is a need to be able to commit the transaction after the view has rendered.

For example displaying a list of users and their user roles you might show the user role using this code: <%: Model.UserRole.Name %>

This will cause a hit on the database as the UserRole is loaded using a NHibernate proxy.

You can fetch the UserRole eage开发者_StackOverflow社区rly which circumvents the issue in this case, but there are cases where it is much faster to use lazy loading.

Anyway, is there a way to run code after the view has rendered?


Have you tried to use session-per-request pattern? It's a very natural way of handling NHibernate sessions in web environment.

There are many information available when you do a Google search on "NHibernate session per request", like this blog post.

Also, take a look at great Bill McCafferty's article NHibernate Best Practices. Although it's written for NHibernate 1.2, it has a wealth of information. While there, his S#arp Architecture also looks very cool :)


How about an action filter?

public class CleanUpAttribute: ActionFilterAttribute
{
    public override void OnResultExecuted(ResultExecutedContext filterContext)
    {
        //cleanup code here
    }
}

Then you decorate your controllers with this attribute.

0

精彩评论

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

关注公众号