1. I have a function DoSomeService with object response as parameter. response are different classes the internal code decides which one to use dynamically at runtime.
2. I have a generic Fluent Validator< T> that takes in the type of a response class, then validates it.
Now, I can do type checking one by one:
public override void DoSomeService(object response) {
object validator = null;
if (response.GetType()==typeof(TypeA_Response)) validator= new Validator<TypeA_Response>();
if (response.GetType()==typeof(TypeB_Response)) validator= new Validator<TypeB_Response>();
if (response.GetType()==typeof(TypeC_Response)) validator= new Validator<TypeC_Response>();
//......
if (response.GetType()==typeof(TypeX_Response)) validator= new Validator<TypeX_Response>();
if (validator.IsValid) {
//do more stuff ...
}
}
But that is not nice, especially when I have many responses. I want something short and generic.
//response could be TypeA_Response, TypeB_Response, TypeX_Response
public override void DoSomeService(object response) {
var validator = new Validator<T>();
if (validator.IsValid) {
//do more stuff ...
}
}
Of course, this won't work because I need to define T for Fluent Validator. How do I detect what type is "object response" and fill it into T dynamically at runtime?
Or how do I avoid doing this all together and have a better structure for my validator< T>?
Note, I can't change the base Service class and DoSomeService function signature, it is an override function from 3rd party package.