C
C#2y ago
joy

asp net core api response using composition over inheritance

hi all, i come across an article creating a BaseResponse class for their API response, but the article also stated that it's better to use Composition over inheritance for the API response, can anyone help advise how does that work? is it to create a response class and register them as a service so that we can return this response class (which is a service) as our API response? thank you so much in advance..
3 Replies
Yawnder
Yawnder2y ago
There is nothing wrong with having a base class for responses, but I'd just base class not in the inheritance kind of way here. You could, for example have this:
class MyApiResponse<T>
{
public string Context { get; set; }
public T Data { get; set; }
public string Next { get; set; }
}
class MyApiResponse<T>
{
public string Context { get; set; }
public T Data { get; set; }
public string Next { get; set; }
}
It's typical for some MS services. MS Graph and MS Dynamics both work like that-ish.
joy
joy2y ago
hmm.. so we use a generic type instead of a specific type
joy
joy2y ago
the article use inheritance like this (advice us to not use this to avoid complexity)