Will
Will

Reputation: 10411

C# WCF abstraction?

Is it possible to declare a base known type and allow all derived types to be transmitted?

[ServiceContract]
public interface IService
{
    [OperationContract]
    [ServiceKnownType(typeof(BaseMsg))]
    object[] Do(BaseMsg msg);
}

Can this be done without declaring every derived type in the IService interface with an attribute?

Upvotes: 1

Views: 172

Answers (2)

Euphoric
Euphoric

Reputation: 12849

Not directly, but if you don't mind creating non-standard service, that can possibly only be consumed by another .NET application, then you can use KnownTypesAttribute using this constructor.

This allows you to create a webservice, that has method, that dynamicaly tells it what types are available for transmision. Then you can use reflection to reflect over all types in loaded assemblies, that derive from your type and add them. But this must be done on both server and client so they understand each other.

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1038720

No, this is not possible. All derived types need to be exposed in the WSDL and thus explicitly specified as such. If you don't want to modify the source code and recompile the web service you could use the <declaredTypes> element in web.config to achieve the same goal:

<system.runtime.serialization>
    <dataContractSerializer>
        <declaredTypes>
            <add type="AppName.BaseType, AppName">
                <knownType type="AppName.KnownType, AppName" />
            </add>
        </declaredTypes>
    </dataContractSerializer>
</system.runtime.serialization>

Upvotes: 3

Related Questions