具有许多程序集的WCF和ServiceKnowType



WCF问题。我在处理多个程序集、继承和数据协定时遇到了问题。

Senario:数据合约二进制文件共享

Common.dll

[DataContract]
public abstract class Command 
{
    [DataMember]
    public Guid Id { get; set; }
    public Command(Guid id)
    {
        Id = id;
    }
}

assembly1.dll

[DataContract]
public class DeleteStuff : Command
{
    public DeleteStuff(Guid id)
        : base(id) { }
    [DataMember]
    public int StuffToDeleteID { get; set; }
}

assembly2.dll

[DataContract]
public class DeleteSomeOtherStuff : Command
{
    public DeleteSomeOtherStuff(Guid id)
        : base(id) { }
    [DataMember]
    public int SomeOtherID { get; set; }
}

服务合同

[ServiceContract]
[ServiceKnownType("GetKnownTypes", typeof(DerivedType))]
public partial interface ICommandsServiceContract
{
    [OperationContract]
    void Execute(IEnumerable<Command> command);
}

DerivedType类,方法GetKnownTypes

public static IEnumerable<Type> GetKnownTypes(ICustomAttributeProvider provider)
    {
        //Works!*!*! but hard-coded, wont work in big picture since i dont know all the classes
        //return new List<Type> { typeof(DeleteSomeOtherStuff), typeof(DeleteStuff) };
        //DOESNT WORK!!
        Type type = typeof(Command);
        IEnumerable<Type> types = AppDomain.CurrentDomain.GetAssemblies().ToList()
            .SelectMany(a => a.GetTypes()
            .Where(t => type.IsAssignableFrom(t)));
        IEnumerable<Type> j = types.ToArray();           
        return j;
    }

如果我在返回j上设置一个断点;如上所述,当服务首次运行时,它具有从Command继承的正确程序集类型。然后,客户端启动,当我向服务发送DeleteSomeOtherStuff时,它就会在SelectMany子句中出现错误。

    Server Error in '/' Application.
Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 
Exception Details: System.Reflection.ReflectionTypeLoadException: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.
Source Error: 

Line 25:                 var type = typeof(Command);
Line 26:                 var types = AppDomain.CurrentDomain.GetAssemblies().ToList()
Line 27:                     .SelectMany(a => a.GetTypes())
Line 28:                     .Where(t => type.IsAssignableFrom(t));
Line 29: 

第27行标记为错误。

当服务第一次运行时,我尝试将数组列表放入一个静态变量中以缓存它,然后当消费者调用它时,它将可用,但出现了相同的错误。

我使用的是客户端的基本通道工厂。

想法??我不能只限于一个程序集。

谢谢!!

在从Command继承的类中,添加[NowType]属性。例如,

[DataContract]
[KnownType(typeof(Command))]
public class DeleteStuff
{
}

最新更新