views:

142

answers:

3

I am trying to pass an object into a WCF web service, the object I am passing in is a Server object, I then want to be able to call TestConnection();

The issue I am having is that Server is the base class and there are several derived classes of Server, i.e. SqlServer2005Server, OracleServer and ODBCServer that I want to use

I want to be able to pass in a Server Object and then determine its type, cast it and then use the method

public string TestServerConnection(Server server)
{
    if (server.ConnectionType == "SqlServer")
    {
        SqlServer2005Server x = (SqlServer2005Server)server;
        // Tests connection to server and returns result
        return x.TestConnection();
    }

    return "";
}

'Server' the base class implements IServer

I am unable to cast it, can you advise?

Much Appreciated

Phill

+1  A: 

You need to add the KnownType declaration to your service contract for each derived class. There are ways to automate this (since it obviously convolutes code and breaks inheritance), but they require a lot of work.

Steve
+1  A: 

Does the object you're passing represent a "live" connection to a DBMS? If the answer is yes, there is no hope of this ever working. Keep in mind that despite the pretty wrapper, the only thing your web service is getting from the caller is a chunk of xml.

Daniel Pratt
+2  A: 

As Daniel Pratt said, in the end, you are only shuttling XML (not always the case, but most of the time you are) across the wire.

If you used a proxy generator to generate the definition of the Server type, then you aren't going to be able to make calls on the methods of Server, because only properties (semantically at least) are used in the proxy definition. Also, you can't cast to the derived types because your instance is really a separate type definition, not the actual base.

If the Server type is indeed the same type (and by same, I mean a reference to the same assembly, not just in name and schema only), then you can do what Steve said and use the KnownType attribute on the Server definition, adding one attribute for each derived class.

However, like he said, that convolutes your code, so be careful when doing this.

I thought that using inversion of control would work here, but you run into the same situation with generic references to specific providers.

casperOne