Is it possible to use generic DataContract's f

2019-07-07 01:46发布

问题:

I know when you create a service you can create a generic DataContract:

[DataContract(Name = "Get{0}Request")
public sealed class GetItemRequest<T>
    where T : class, new() { ... }

[DataContract(Name = "Get{0}Response")
public sealed class GetItemResponse<T>
    where T : class, new() { ... }

[ServiceContract]
public void MyService : IMyService
{
    [OperationContract]
    GetItemResponse<Foo> GetItem(GetItemRequest<Foo> request);
}

This generates a GetFooRequest and GetFooResponse definition for my WSDL. Now, what I'm curious about is if it is possible to go in the other direction?

Is it possible to create a client that uses the Generic DataContracts and pass those to the server as a concrete object? I attempted this after adding a Service Reference and it didn't really work out so well. So this is more of me wondering if there is any way (even if it means not adding a Service Reference) to do this?

回答1:

Ultimately, WCF is going to look at the contract class. If that is generated from WSDL/MEX it won't have this (since this isn't how it is expressed in the metadata) - but if your client has the code as above, then sure it should work fine.

If you add a library reference (i.e. a dll / project reference) to your DTO dll from the client, and ensure WCF has shared-assemblies enabled, it should work. If it still baulks, then cheat: use a service reference just to get the config data. Then delete the service reference but keep the configuration (those config files are a pain otherwise). Then it should locate the type from the library.