2

是否可以将 Servicestack 服务注册为 MVC 控制器中的属性?我问是因为我遇到了与此问题类似的问题:超时已过期。- 在 ServiceStack 服务中使用 Db,当我在 MVC 控制器中太快调用此操作时,我会收到超时:

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);
}

商品服务:

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 操作中的属性,如下所示:

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

而不是:

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

1 回答 1

2

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

有关在 ServiceStack 和 MVC 之间共享逻辑的其他方式,请参阅此答案。

于 2013-11-21T13:31:43.633 回答