Is it possible to use one generic / abstract service in ServiceStack?

I am developing (hopefully) a RESTful API using ServiceStack.

I noticed that most of my services look the same, for example, the GET method will look something like this:

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

says that I have 20 resources, 20 DTO requests, so I got about 20 services of the same template more or less ...

I tried to create a generic or abstract service so that I could create inheriting services that simply implement the appropriate behavior, but I got stuck because DTO requests were not needed for serialization.

Is there any way to do this?

EDIT:

An example of what I'm trying to do:

 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(); } } 
+4
source share
1 answer

To do this in the new API , we implemented the IServiceRunner concept, which separates the execution of your service from its implementation.

To add your own Hooks for services, you just need to override the standard service Runner in AppHost from its default implementation:

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

With your own:

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

Where MyServiceRunner is just a custom class that implements custom hooks that interest you, for example:

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

Also, for smaller error handling options, check out the error handling wiki page .

+4
source

All Articles