public static IProducer <T> GetStaticProducer <T>(this StaticPortMetadata portMetadata, PortConfiguration portConfiguration, object instance) { /* old implementation * dynamic obj = GetStaticConnector(instance, portMetadata, portConfiguration); * return (IProducer<T>)obj; */ object obj = GetStaticConnector(instance, portMetadata, portConfiguration); var objType = obj.GetType(); if (typeof(IProducer <T>).IsAssignableFrom(objType)) { return((IProducer <T>)obj); } if (objType.IsGenericType) { var interfaceName = typeof(IProducer <>).Name;//should be "IProducer`1" var @interface = objType.GetInterface(interfaceName); if (@interface != null) { var typeArg = @interface.GetGenericArguments().Single(); if (typeArg.CanBeAssignedOrCastTo(typeof(T))) { var methodInfo = typeof(HelperExtensions).GetMethod(nameof(Cast)).MakeGenericMethod(new[] { typeArg, typeof(T) }); var result = (IProducer <T>)methodInfo.Invoke(obj: null, new[] { (dynamic)obj, false }); return(result); } } } throw new InvalidOperationException("returned object is not a valid type"); }
private static dynamic GetStaticConnector(this object instance, StaticPortMetadata portMetadata, PortConfiguration portConfiguration) { Debug.Assert(Equals(portMetadata.Identifier, portConfiguration.Identifier)); dynamic prop = portMetadata.Property.GetValue(instance); if (prop is null) { throw new Exception("instance connector is null"); } switch (portMetadata.Aggregation) { case PortAggregation.Object: return(prop); case PortAggregation.List: return(prop[(int)portConfiguration.Index]); case PortAggregation.Dictionary: return(prop[(string)portConfiguration.Index]); default: throw new InvalidOperationException(); } }
public static IConsumer <T> GetStaticConsumer <T>(this StaticPortMetadata portMetadata, PortConfiguration portConfiguration, object instance) { dynamic obj = GetStaticConnector(instance, portMetadata, portConfiguration); return((IConsumer <T>)obj); }