Is it possible to have one interface that multiple services implement but can pass differing params and have differing responses on the different methods?
Here's an example of what I would like to do.
ServiceA example
public class ZParams{}
public class ZResponse{}
public class YParams{}
public class YResponse{}
public class ServiceA : IService
{
public ZResponse Get(ZParams @params)
{
///
}
public YResponse Method2(YParams @params)
{
///
}
}
ServiceB example
public class FParams{}
public class FResponse{}
public class GParams{}
public class GResponse{}
public class ServiceB : IService
{
public FResponse Get(FParams @params)
{
///
}
public GResponse Method2(GParams @params)
{
///
}
}
Any help is much appreciated.
CodePudding user response:
Another option is to use generics which does not require the responses to conform to the same interface. Adding the processing to the params class lets each type return the proper response.
public interface IReturns<T> where T: new() {
T Get();
}
public class ZResponse
{
public string FullName { get; set; }
}
public class ZParams : IReturns<ZResponse>
{
public string FirstName { get; set; }
public string LastName { get; set; }
public ZResponse Get()
{
return new ZResponse { FullName = $"{FirstName} {LastName}" };
}
}
public class YResponse
{
public string StreetAddress { get; set; }
}
public class YParams : IReturns<YResponse>
{
public int Number { get; set; }
public string StreetName { get; set; }
public YResponse Get()
{
return new YResponse { StreetAddress = $"{Number} {StreetName}" };
}
}
//in IService
public T Get<T>(IReturns<T> param) where T: new()
{
return param.Get();
}
CodePudding user response:
You can use a "marker" interface - your implementation Get()
would need to interrogate the type passed in to determine if it's a ZParams
or YParams
and act accordingly.
public interface IParams {}
public interface IResponse {}
public class ZParams : IParams {}
public class ZResponse : IResponse {}
public class YParams : IParams {}
public class YResponse : IResponse{}
public interface IService : {
IResponse Get(IParams @params);
}
public class ServiceA : IService
{
public IResponse Get(IParams @params)
{
///
}
}