internal bool TryGetUserActivatedInstance(Type t, CreateInstanceContext context, out object activated) { activated = null; if (this.activators.TryGetValue(t, out var a)) { activated = a(context); return(true); } return(false); }
public object CreateInstance(Type type, CreateInstanceContext cx) { if (CustomCreateInstanceWith != null) { var instance = CustomCreateInstanceWith(type, cx); return instance; } else { var targetTypeDescription = TypeDescriptor.DescribeType(type); var instance = targetTypeDescription.CreateInstance(); return instance; } }
// todo context should be local to serialzation (type) // todo: this may also try to reuse type mapper code rather than copy it protected bool TryCreateInstace(Type targetType, CreateInstanceContext create_cx, out object newInstance) { newInstance = null; try { if (CustomCreateInstanceWith != null) { try { newInstance = CustomCreateInstanceWith(targetType, create_cx); return true; } catch (Exception ex) { throw; } } var constructor = targetType .GetConstructor( BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, binder: null, types: Type.EmptyTypes, modifiers: null); if (constructor != null) { newInstance = constructor.Invoke(null); return true; } } catch (Exception ex) { ex.TryAddContextData("target type", () => targetType.FullName); InternalTrace.Information(ex, "Failed to create instance of type."); } return false; }
internal object GetActivatedInstance(Type t, CreateInstanceContext context) { if (this.activators.TryGetValue(t, out var a)) { return(a(context)); } else { try { return(Activator.CreateInstance(t)); } catch (MissingMethodException exc) { throw new InvalidOperationException(string.Format( "Failed to create type '{1}'. Only types with a " + "parameterless constructor or an specialized creator can be created. Make sure the type has " + "a parameterless constructor or a configuration with an corresponding creator is provided.", exc.Message, t.FullName)); } } }