Rob Rob - 5 days ago 5
C# Question

C# Type Constraint (PushSharp)

I'm trying to create a generic way of using (external assembly) Types who all inherit from the same Type.

The external assembly in question is the

PushSharp
library.
The Types look like this:

/* First instance */
public class ApnsServiceBroker : ServiceBroker<ApnsNotification>
{
public ApnsServiceBroker(ApnsConfiguration configuration) : base(new ApnsServiceConnectionFactory(configuration)) { }
}

/* Second instance */
public class GcmServiceBroker : ServiceBroker<GcmNotification>
{
public GcmServiceBroker(GcmConfiguration configuration) : base(new GcmServiceConnectionFactory(configuration)) { }
}

/* More instances */
...


The
ServiceBroker
class inherits from
IServiceBroker<INotification>
and the
GcmNotification
and
ApnsNotification
inherit from
INotification
.
These classes are all inside the external assemby, and I cannot change them.

What I'm trying to achieve is something like this:

public IBroker ResolveBroker()
{
// Some unrelated logic to determine which broker to use, could be any of the broker instances

// Return one of them for example's sake
return new ApnsServiceBroker(new ApnsConfiguration());
}


But I'm running into some trouble defining the
IBroker
interface. I have tried quite a few different options already but can't seem to figure this one out.

Another additional difficulty is that the
Broker
instances each expect a different
Configuration
object in the constructor. These
Configuration
objects do NOT inherit from anything.

Here's a few of my attempts:

/* First attempt: Figured I could just use this directly */
ServiceBroker<INotification> broker;
broker = new ApnsServiceBroker(); //Cannot simplicity convert type ApnsServiceBroker to ServiceBroker<INotification>

/* Second attempt: Don't know what to pass as T and can't seem to pass anything in the base's constructor. */
public interface IBroker<T> where T : ServiceBroker<INotification>


I very rarely ask questions here, but I'm completely stuck.
I spent quite some time digging through MSDN and other questions here, but none of them seem to match my situation exactly.

Answer

Not being familiar with pushsharp, I would think think this would work:

public IServiceBroker<INotification> ResolveBroker()
{
    // Some unrelated logic to determine which broker to use, could be any of the broker instances

    // Return one of them for example's sake
    return (IServiceBroker<INotification>) new ApnsServiceBroker(new ApnsConfiguration());
}
Comments