gpt4 book ai didi

api - 是否可以在 ServiceStack 中使用一种通用/抽象服务?

转载 作者:行者123 更新时间:2023-12-03 21:26:00 25 4
gpt4 key购买 nike

我正在使用 ServiceStack 开发一个(希望如此)RESTful API。

我注意到我的大多数服务看起来都是一样的,例如,GET 方法看起来会是 某事像这样:

        try
{
Validate();
GetData();
return Response();
}
catch (Exception)
{
//TODO: Log the exception
throw; //rethrow
}

假设我有 20 个资源,20 个请求 DTO,所以我或多或少地获得了大约 20 个相同模板的服务......

我试图创建一个通用或抽象的服务,以便我可以创建仅实现相关行为的继承服务,但我被卡住了,因为请求 DTO 不是序列化所需要的。

有什么办法吗?

编辑:

我正在尝试做的一个例子:
public abstract class MyService<TResponse,TRequest> : Service
{
protected abstract TResponse InnerGet();
protected abstract void InnerDelete();
public TResponse Get(TRequest request)
{
//General Code Here.
TResponse response = InnerGet();
//General Code Here.
return response;
}

public void Delete(TRequest request)
{
//General Code Here.
InnerDelete();
//General Code Here.
}
}

public class AccountService : MyService<Accounts, Account>
{

protected override Accounts InnerGet()
{
throw new NotImplementedException();//Get the data from BL
}

protected override void InnerDelete()
{
throw new NotImplementedException();
}
}

最佳答案

New API 中执行此操作我们引入了 IServiceRunner 的概念,它将服务的执行与服务的实现分离。

要添加您自己的服务 Hook ,您只需从默认实现中覆盖 AppHost 中的默认服务运行程序:

public virtual IServiceRunner<TRequest> CreateServiceRunner<TRequest>(ActionContext actionContext)
{
return new ServiceRunner<TRequest>(this, actionContext); //Cached per Service Action
}

用你自己的:
public override IServiceRunner<TRequest> CreateServiceRunner<TRequest>(ActionContext actionContext)
{
return new MyServiceRunner<TRequest>(this, actionContext); //Cached per Service Action
}

MyServiceRunner 只是一个实现您感兴趣的自定义钩子(Hook)的自定义类,例如:
public class MyServiceRunner<T> : ServiceRunner<T> {
public override void OnBeforeExecute(IRequestContext requestContext, TRequest request) {
// Called just before any Action is executed
}

public override object OnAfterExecute(IRequestContext requestContext, object response) {
// Called just after any Action is executed, you can modify the response returned here as well
}

public override object HandleException(IRequestContext requestContext, TRequest request, Exception ex) {
// Called whenever an exception is thrown in your Services Action
}
}

此外,对于更细粒度的错误处理选项,请查看 Error Handling wiki page .

关于api - 是否可以在 ServiceStack 中使用一种通用/抽象服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14579756/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com