3
votes

I'm a newbie with ServiceStack and to learn how it works, I'll develop a web API for Northwind database (using the repository pattern).

I've checked the sample project ServiceStack.Northwind and there are only two services (Customers and Orders). I'd like to develop a complete API (Customers, Orders, Products, etc..). Something like Matt Cowan has done.

Basically, all services would do the same for any operation:

  • Receive a request.
  • Execute (Repository.Get, Repository.Add, Repository.Update, Repository.Delete).
  • Send back a response.

For this, I thought about making a base class to do almost all the work. First I started with something like:

public class BaseService<TRepository, TEntity, TDto> : Service
{
    ...
}

The problem of this class is that I don't know the types for request and response for each operation. So I thought I'd pass them as type arguments:

public class BaseService<TRepository, TEntity, TDto, TRequest, TSingleResponse, TCollectionResponse> : Service
{
    ...
}

I don't like this. I'm sure It can be done without passing n type arguments to the class.

How would I approach the development of this base class?.

Thank you very much in advance.

1

1 Answers

2
votes

You may reduce the number of type arguments by using the following suggestions:

  • Use TEntity as your request/response for operations on a single entity
  • Declare repository interface IRepository<TEntity> to avoid the repository type argument

As for the operations that return a list for entities (eg. FindCustomers, FindOrders) - each operation will probably have unique search parameters and you will need to implement it in the derived class anyway.

public class BaseEntity
{
    public int Id { get; set; }
    // ...
}

public interface IRepostory<TEntity> where TEntity : BaseEntity
{
    IList<TEntity> GetAll();

    TEntity Get(int id);

    void Save(TEntity entity);
    // ...
}

public class BaseService<TEntity, TCollectionRequest> : Service
    where TEntity : BaseEntity
{
    public IRepository<TEntity> Repository { get; set; }

    public virtual object Get(TEntity request)
    {
        return Repository.Get(request.Id);
    }

    public virtual object Get(TCollectionRequest request)
    {
        return Repository.GetAll();
    }

    public virtual object Post(TEntity request)
    {
        Repository.Save(request);
        return request;
    }

    public virtual object Put(TEntity request)
    {
        // ...
    }
    // ...
}