I found a solution and it worked!
I use ServiceKnownTypethat load types that members implement ServiceKnownTypefor DataContract.
For instance:
I have an interface for animals:
public interface IAnimal
{
string Name { get; }
void MakeSound();
}
and implementation (the interface does not know the types of implementation):
public class Cat : IAnimal
{
public string Name =>"Kitty";
public void MakeSound()
{
Console.WriteLine("Meeeee-ow!");
}
}
public class Dog : IAnimal
{
public string Name => "Lucy";
public void MakeSound()
{
Console.WriteLine("Wolf Wolf!");
}
}
To use the types Catand Dogthat implement the interface IAnimalin the service:
public interface IAnimalService: IAnimalService
{
IAnimal GetDog();
void InsertCat(IAnimal cat);
}
I can use an attribute ServiceKnownTypethat will load the type by interface type.
I Created a static class that returns all types IAnimal:
public static class AnimalsTypeProvider
{
public static IEnumerable<Type> GetAnimalsTypes(ICustomAttributeProvider provider)
{
IEnumerable<Type> typesThatImplementIAnimal = GetAllTypesThatImplementInterface<IAnimal>();
return typesThatImplementIAnimal;
}
public static IEnumerable<Type> GetAllTypesThatImplementInterface<T>()
{
Type interfaceType = typeof(T);
var assemblies = AppDomain.CurrentDomain.GetAssemblies();
List<Type> typeList = new List<Type>();
assemblies.ToList().ForEach(a => a.GetTypes().ToList().ForEach(t => typeList.Add(t)));
var alltypesThaImplementTarget =
typeList.Where(t => (false == t.IsAbstract) && t.IsClass && interfaceType.IsAssignableFrom(t));
return alltypesThaImplementTarget;
}
}
AnnimalsTypeProvider GetAnimalsTypes :
[ServiceContract]
[ServiceKnownType("GetAnimalsTypes", typeof(AnimalsTypeProvider))]
public interface IServicesServer : IAnimalService
{
IAnimal GetDog();
void InsertCat(IAnimal cat);
}
!
IAnimal Cat Dog - .