解决MVC控制器中的ServiceStack服务

时间:2013-11-21 13:14:02

标签: servicestack funq

是否可以将Servicestack服务注册为MVC控制器中的属性?我问,因为我遇到了与此问题类似的问题:Timeout expired. - Using Db in ServiceStack Service当我在MVC控制器中过快地调用此Action时,我收到超时:

BaseController(我的所有控制器都继承自此):

public class BaseController : Controller
{
    public GoodsInService GoodsInService { get; set; }
    public GoodsInProductService GoodsInProductService { get; set; }
    public ReturnTypeService ReturnTypeService { get; set; }
}

GoodsInController:

public ActionResult Details(int id)
{
    var goodsIn = GoodsInService.Get(new GoodsIn
    {
        Id = id
    });

    return View(goodsIn);
}

GoodsInService:

public GoodsIn Get(GoodsIn request)
{
    var goodsIn = Db.Id<GoodsIn>(request.Id);

    using (var goodsInProductSvc = ResolveService<GoodsInProductService>())
    using (var returnTypeSvc = ResolveService<ReturnTypeService>())
    {
        goodsIn.GoodsInProducts = goodsInProductSvc.Get(new GoodsInProducts
        {
            GoodsInId = goodsIn.Id
        });
        goodsIn.ReturnType = returnTypeSvc.Get(new ReturnType
        {
            Id = goodsIn.ReturnTypeId
        });
    }

    return goodsIn;
}

修改

作为一项解决方法,我已完成以下操作并删除了我的容器中的服务注册,根据@mythz下面的答案,这似乎解决了我的问题:

public class BaseController : ServiceStackController
{
    public GoodsInService GoodsInService { get; set; }
    public GoodsInProductService GoodsInProductService { get; set; }
    public ReturnTypeService ReturnTypeService { get; set; }

    protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        GoodsInService = AppHostBase.ResolveService<GoodsInService>(System.Web.HttpContext.Current);
        GoodsInProductService = AppHostBase.ResolveService<GoodsInProductService>(System.Web.HttpContext.Current);
        ReturnTypeService = AppHostBase.ResolveService<ReturnTypeService>(System.Web.HttpContext.Current);

        base.OnActionExecuting(filterContext);
    }

    protected override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        GoodsInService.Dispose();
        GoodsInProductService.Dispose();
        ReturnTypeService.Dispose();

        base.OnActionExecuted(filterContext);
    }
}

这样,我可以将我的服务用作MVC Action中的属性,如下所示:

goodsIn = GoodsInService.Get(new GoodsIn
{
    Id = id
});

而不是:

using (var goodsInSvc = AppHostBase.ResolveService<GoodsInService>
          (System.Web.HttpContext.Current))
{
    goodsIn = goodsInSvc.Get(new GoodsIn
    {
        Id = id
    });
}

1 个答案:

答案 0 :(得分:2)

不要在IOC中重新注册ServiceStack服务,因为它们已经由ServiceStack注册。如果你想在MVC控制器中调用ServiceStack服务,只需使用已发布的AppHostBase.ResolveService<T> API,它只是从IOC解析服务并注入当前请求上下文。

有关sharing logic between ServiceStack and MVC的其他方法,请参阅此答案。