私は解決策を見つけました。
ServiceKnownType
を実装するタイプをロードするServiceKnownType
を使用しています(DataContract
メンバー用)。例えば
:
私は動物のインタフェースを持っている:
public interface IAnimal
{
string Name { get; }
void MakeSound();
}
と実装(インターフェース実装タイプを知りません):
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!");
}
}
Cat
とDog
タイプを使用するためのものサービス内にIAnimal
インターフェイスを実装します。
public interface IAnimalService: IAnimalService
{
IAnimal GetDog();
void InsertCat(IAnimal cat);
}
インターフェイスタイプによってタイプをロードする属性ServiceKnownType
を使用できます。
私はすべてのIAnimal
種類返す静的クラス作成:
public static class AnimalsTypeProvider
{
public static IEnumerable<Type> GetAnimalsTypes(ICustomAttributeProvider provider)
{
//Get all types that implement animals.
//If there is more interfaces or abtract types that been used in the service can be called for each type and union result
IEnumerable<Type> typesThatImplementIAnimal = GetAllTypesThatImplementInterface<IAnimal>();
return typesThatImplementIAnimal;
}
public static IEnumerable<Type> GetAllTypesThatImplementInterface<T>()
{
Type interfaceType = typeof(T);
//get all aseembly in current application
var assemblies = AppDomain.CurrentDomain.GetAssemblies();
List<Type> typeList = new List<Type>();
//get all types from assemblies
assemblies.ToList().ForEach(a => a.GetTypes().ToList().ForEach(t => typeList.Add(t)));
//Get only types that implement the IAnimal interface
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);
}
をし、それはそれです!
サービスをロードしているときに、既知のタイプのすべてのタイプが動的モードでロードされます。構成はまったくなく、Cat
とDog
になります。
あなたが再設計する必要があるようなサウンドです。あなたのインターフェイスプロジェクトは実装に依存してはいけません。 – Crowcoder
これは私が避けようとしていることです。私のデザインは、インターフェイスと実装の分離を持っているので、インターフェイス上でKnownTypes属性を使用することはできません。 –