I solved this with a new (but not so neat) factory.
If anyone can help me tidy this up then I would be greatful
public delegate FlightData.Model.Flight GetFlightById(string flightId);
public delegate List<flightdata.model.flight> GetFlights();
public static class FlightDataFactory
{
public static GetFlightById GetFlightByIdDataMethod(Type iFlightDataWorker)
{
if (!iFlightDataWorker.GetType().GetInterfaces().Contains(typeof(Interface.IFlightDataWorker)))
throw new ArgumentException(string.Format("The type {0} does not implement the interface {1}.", iFlightDataWorker.Name, typeof(Interface.IFlightDataWorker).Name), "iFlightDataWorker");
object worker = iFlightDataWorker.GetConstructor(Type.EmptyTypes).Invoke(new object[]{});
return delegate(string flightId)
{
return (FlightData.Model.Flight)iFlightDataWorker.GetMethod("GetFlightData").InvokeWithExceptions(worker, new object[] { flightId });
};
}
public static GetFlights GetFlightDataMethod(Type iFlightDataWorker)
{
if (!iFlightDataWorker.GetType().GetInterfaces().Contains(typeof(Interface.IFlightDataWorker)))
throw new ArgumentException(string.Format("The type {0} does not implement the interface {1}.", iFlightDataWorker.Name, typeof(Interface.IFlightDataWorker).Name), "iFlightDataWorker");
object worker = iFlightDataWorker.GetConstructor(Type.EmptyTypes).Invoke(new object[] { });
return delegate
{
return (List<flightdata.model.flight>)iFlightDataWorker.GetMethod("GetFlightData").InvokeWithExceptions(worker, new object[] { });
};
}
}</flightdata.model.flight></flightdata.model.flight>
I have also created a handy Extension method so I get past targetinvocationexceptions which I would hope not to get.
public static object InvokeWithExceptions(this MethodInfo methodInfo, object obj, params object[] parameters)
{
try
{
return methodInfo.Invoke(obj, parameters);
}
catch (TargetInvocationException exception)
{
if (exception.InnerException != null)
throw exception.InnerException;
throw;
}
}