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.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s