I have a .net core 3.1 api and I want to version my controllers and I think some structure for versioning on service layer like below
public interface IVersionableObject { }
public class GetDataV1 : IVersionableObject { }
public class PostDataV1 : IVersionableObject { }
public class GetDataV2 : IVersionableObject { }
public class PostDataV2 : IVersionableObject { }
public class ListItemV1 : IVersionableObject { }
public class MobileAppServiceV1
{
public virtual async Task<IVersionableObject> Get()
{
return new GetDataV1();
}
public virtual async Task<IVersionableObject> Post()
{
return new PostDataV1();
}
public virtual async Task<IVersionableObject> ListItems()
{
return new ListItemV1();
}
}
public class MobileAppServiceV2 : MobileAppServiceV1
{
public override async Task<IVersionableObject> Get()
{
return new GetDataV2();
}
public override async Task<IVersionableObject> Post()
{
return new PostDataV2();
}
[Obsolete("This method is not available for after V1" , true)]
public async Task<IVersionableObject> ListItems()
{
throw new NotSupportedException("This method is not available for after V1");
}
}
Lets check Controller
Controller for V1
[ApiVersion("1.0")]
[Route("api/{v:apiVersion}/values")]
public class ValuesControllerV1 : ControllerBase
{
private readonly MobileAppServiceV1 _mobileAppServiceV1;
public ValuesControllerV1()
{
_mobileAppServiceV1 = new MobileAppServiceV1();
}
[HttpGet]
public async Task<IActionResult> Get()
{
return Ok(await _mobileAppServiceV1.Get());
}
[HttpGet("listItem")]
public async Task<IActionResult> ListItems()
{
return Ok(await _mobileAppServiceV1.ListItems());
}
[HttpPost]
public async Task<IActionResult> Post([FromBody] string value)
{
return Ok(await _mobileAppServiceV1.Post());
}
}
Controller for V2
[ApiVersion("2.0")]
[Route("api/{v:apiVersion}/values")]
public class ValuesControllerV2 : ControllerBase
{
private readonly MobileAppServiceV2 _mobileAppServiceV2;
public ValuesControllerV2()
{
_mobileAppServiceV2 = new MobileAppServiceV2();
}
[HttpGet]
public async Task<IActionResult> Get()
{
return Ok(await _mobileAppServiceV2.Get());
}
[HttpPost]
public async Task<IActionResult> Post([FromBody] string value)
{
return Ok(await _mobileAppServiceV2.Post());
}
}
For example ListItems method removed on v2 , I avoid to use ListItem method on v2 with Obselete
attribute.
Finally I think structure something like this and I try to show it with sample code.Can you give some idea about this is good structure or not for versioning service layer on web api? I am open to all suggestions.