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

api, rest, servicestack

Solution

To do this in the New API we've introduced the concept of a IServiceRunner that decouples the execution of your service from the implementation of it.

To add your own Service Hooks you just need to override the default Service Runner in your 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 implementing the custom hooks you're interested in, e.g:

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 more fine-grained Error Handling options check out the Error Handling wiki page.

Problem

I am developing a (hopefully) RESTful API using ServiceStack. I noticed that most of my services look the same, for example, a GET method will look something like this: ``` try { Validate(); GetData(); return Response(); } catch (Exception) { //TODO: Log the exception throw; //rethrow } ``` lets say I got 20 resources, 20 request DTOs, so I got about 20 services of the same template more or less... I tried to make a generic or abstract Service so I can create inheriting services which just implement the relevant behavior but I got stuck because the request DTOs weren't as needed for serialization. Is there any way to do it? EDIT: an Example for 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(); } } ```

Original source