在ServiceStack中动态创建操作和服务

我正在开发一个ServiceStack项目,它要求我收集一个命令列表,我有200多个命令,并为每个命令创建一个操作和服务。 基本上我正在制作一个命令API,它允许用户在不使用UI的情况下发送命令(暴露我的命令)。

我正在尝试做的一个简单示例:(应用程序启动)

Gather all commands (with some exemptions) for each command make an operation and service for that command map the commands attributes to the new operation and service 

我遇到的问题是创建运营和服务。 我不确定它是否在ServiceStack框架内得到支持,以允许动态创建服务和操作,但我真的没有找到一种方法来做到这一点。 为了澄清,动态我的意思是在应用程序启动期间从列表中创建命令,而不是动态创建它们。

有人可以为我的理解提供一些启示吗?

我感谢任何帮助,

麦克风

委托给多个内部服务的单一服务

我首先考虑使用一个使用自由通配符路由的服务实现来接受多个请求类型,然后根据一些参数委托给不同的服务实现,例如:

 [Route("/services/{Type}/{PathInfo*})] public class DynamicService { public string Type { get; set; } public string PathInfo { get; set; } } public class DynamicServices : Service { public object Any(DynamicService request) { if (request.Type == "type1") { //Resolve existing Service and call with converted Request DTO using (var service = base.ResolveService()) { return service.Any(request.ConvertTo()); } } else if (request.Type == "type2") { ... } } } 

动态生成和注册服务实现

否则,您可以查看ServiceStack的AutoQuery实现,以获取有关如何动态生成和注册动态服务的示例。 AutoQuery查找实现IQuery<>接口的Request DTO然后生成并注册使用它的新Service实现。

它本质上与定义的Service类的工作方式相同,不是使用注册现有的Service类型,而是使用代码生成来动态创建Service实现,然后可以使用以下方法注册:

 appHost.RegisterService(serviceType); 

ServiceStack还支持在运行时动态注册属性 ,例如:

 requestDtoType .AddAttributes(new RouteAttribute("/custom-route")) .AddAttributes(new RestrictAttribute(RequestAttributes.Json));