Vagif Abilov's blog on .NET

How to programmatically define known types in WCF

WCF behavior typically can be specified in three ways: using attributes, using configuration files and programmatically. Although KnownType concept also falls in this category, it is impossible to find any reference or example of how to define a WCF known type programmatically. One of the most comprehensive blog entries on this subject even called “All About Known Type” does not even mention that they can be controlled directly from the application code. Search in Microsoft’s WCF forum brought me a hint to add known types to a collection available at contract endpoint.

After a few trials and failures I came up with the following implementation:

1. On the server side known types must be added to the service host after its creation and before it is open:

ServiceHost host = new ServiceHost(typeof(CustomerManager), new Uri("http://localhost:8000/"));
foreach (var endpoint in host.Description.Endpoints)
{
    foreach (var operation in endpoint.Contract.Operations)
    {
        operation.KnownTypes.Add(typeof(MyDynamicallyAddedKnownType));
    }
}
host.Open();

2. On the client side known types are added after the creation of proxy:

foreach (var operation in proxy.Endpoint.Contract.Operations)
{
    operation.KnownTypes.Add(typeof(MyDynamicallyAddedKnownType));
}

This should do!

Disclaimer: I am not advocating use of known types! In fact, I dislike (or even hate) WCF known types. So this is just an excercise. In something we probably should not be making a part of our core design.

Comments

Jeff said:

Thanks for this.  The host side seems to work but for some reason the proxy is not...it still claims it can't find the added types.  Any thoughts?

# June 2, 2009 1:01 AM

Andrew Rea said:

I have been looking into this lately for a specific reason.  Some integration tests I want to write

# June 7, 2010 12:52 AM

Raja said:

Please mention binding details of wcf

# June 29, 2010 1:33 PM
Leave a Comment

(required) 

(required) 

(optional)

(required) 


Please add 4 and 4 and type the answer here: