具有许多程序集的WCF和ServiceKnownType

时间:2011-07-03 23:34:24

标签: wcf reflection

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行被标记为错误。

我尝试将数组列表放在静态变量中,以便在服务首次运行时对其进行缓存,然后在消费者调用但具有相同错误时可用。

我正在使用客户端的基本渠道工厂。

想法?我不能限制一个组装。

谢谢!

1 个答案:

答案 0 :(得分:-1)

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

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