0

In my project, I have several types of Web API controllers (and their corresponding services and repositories). When I started out, I made an interface of a generic type that would describe the basic functionality every controller/service/repository should have.

Since then, there have been new types of entities that these controllers need to handle. For example, before, we only had to handle a basic Entity with an int32 ID, and several other fields. Now, we need to handle child entities, and entities with a string instead of int32 ID.

I've solved this by creating these interfaces:

interface IService<T>
{
    List<T> GetAll();
    T Get(long id);
    // ...
}

interface IChildService<T>
{
    List<T> GetAll(long id);
    T Get(long id);
    // ...
}

interface IStrService<T>
{
    List<T> GetAll();
    T Get(string id);
    // ...
}

interface IChildStrService<T>
{
    List<T> GetAll(string id);
    T Get(string id);
    // ...
}

It works, but I hate everything about it. I want to be able to reference a service by declaring IService<ObjType>, not use IStrService here and IChildService there.

Is there any way I can redesign this to be more generic, abstract and supporting my current situation? I've been thinking along the lines of abstracting my ID type, so that it doesn't matter what it is - a string or int, or whatever comes up in the future. I'm not sure how to handle ChildServices though, as they need the parent's ID to return a list of results.

I should also mention, that in the very first implementation, we used this:

interface IService<T>
{
    List<T> GetAll();
    List<T> GetAll(long parentId);
    List<T> GetAll(string parentId);
    // ...
}

But as you can imagine, this became very cluttered, and I think it beats the purpose of interfaces if I'm just going to define 50% of the methods with a NotImplementedException.

2
  • You could add the type of the ID (int or string) as a second type parameter in the generics. Regarding ChildServices, who supplies the parent ID? Is there any way you could make the child service remember its parent's ID so that you don't need to supply it every time you want to use it?
    – Doval
    Commented Oct 30, 2014 at 12:26
  • Thanks - didn't know that. I just realized myself that the parentId is in the model, so when I'm sending a model to Update, for example, it doesn't need to supply its parentId separately. The only place I'd need the parentId is in the GetAll then, since it should only return rows in that parent - not all of them. Commented Oct 30, 2014 at 12:32

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.