asp.net-web-api – 使用WebAPI和RavenDB进行基本会话处理

前端之家收集整理的这篇文章主要介绍了asp.net-web-api – 使用WebAPI和RavenDB进行基本会话处理前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
用这个作为基础APIController,想法?主要是对处理dispose中的savechanges感到好奇,而不是我在其他地方看到的ExecuteAsync方法
using System;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Controllers;
using Raven.Client;
using Raven.Client.Document;

public abstract class RavenDbController : ApiController
{
    private IDocumentStore _documentStore;

    public IDocumentStore Store
    {
        get { return _documentStore ?? (_documentStore = LazyDocStore.Value); }
        set { _documentStore = value; }
    }

    protected override void Initialize(HttpControllerContext controllerContext)
    {
        Session = Store.OpenSession();
        base.Initialize(controllerContext);
    }

    protected override void Dispose(bool disposing)
    {
        using (Session)
        {
            Session.SaveChanges();
        }
    }

    public IDocumentSession Session { get; set; }

}

解决方法

我更喜欢使用动作过滤器属性来管理基本API控制器上的会话对象的生命周期.请参阅以下代码以演示此方法
public class RavenSessionManagementAttribute : ActionFilterAttribute
{
    private readonly IDocumentStore store;

    public RavenSessionManagementAttribute(IDocumentStore store)
    {
        if (store == null) throw new ArgumentNullException("store");    
        this.store = store;
    }

    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        var controller = actionContext.ControllerContext.Controller as AbstractApiController;
        if (controller == null)
            return;

        // Can be set explicitly in unit testing
        if (controller.RavenSession != null)
            return;

        controller.RavenSession = store.OpenSession();
        controller.RavenSession.Advanced.USEOptimisticConcurrency = true;
    }

    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
        var controller = actionExecutedContext.ActionContext.ControllerContext.Controller as AbstractApiController;
        if (controller == null)
            return;

        using (var session = controller.RavenSession)
        {
            if (session == null)
                return;

            if (actionExecutedContext.Exception != null)
            {
                session.SaveChanges();
            }
        }
    }
}

FilterConfig.cs:

public class FilterConfig
    {
        public static void RegisterGlobalFilters(HttpFilterCollection filters)
        {
            filters.Add(new RavenSessionManagementAttribute(DocumentStoreHolder.Store));
        }
    }

AbstractApiController.cs:

public abstract class AbstractApiController : ApiController
    {
        public IDocumentSession RavenSession { get; set; }
    }
原文链接:https://www.f2er.com/aspnet/246844.html

猜你在找的asp.Net相关文章