| | | 1 | | using Elsa.Workflows; |
| | | 2 | | |
| | | 3 | | namespace Elsa.Dsl.ElsaScript.Helpers; |
| | | 4 | | |
| | | 5 | | internal static class ActivityActivator |
| | | 6 | | { |
| | | 7 | | public static IActivity Create(Type type) |
| | | 8 | | { |
| | | 9 | | // Try parameterless ctor first (fast path) |
| | 2 | 10 | | var parameterless = type.GetConstructor(Type.EmptyTypes); |
| | 2 | 11 | | if (parameterless != null) |
| | 0 | 12 | | return (IActivity)parameterless.Invoke([]); |
| | | 13 | | |
| | | 14 | | // Fall back: pick a public ctor and provide default values for args |
| | 2 | 15 | | var ctor = type |
| | 2 | 16 | | .GetConstructors() |
| | 14 | 17 | | .OrderBy(c => c.GetParameters().Length) // shortest first |
| | 2 | 18 | | .FirstOrDefault() |
| | 2 | 19 | | ?? throw new InvalidOperationException( |
| | 2 | 20 | | $"Type {type} has no public constructors and cannot be instantiated."); |
| | | 21 | | |
| | 2 | 22 | | var parameters = ctor.GetParameters(); |
| | 2 | 23 | | var args = new object?[parameters.Length]; |
| | | 24 | | |
| | 16 | 25 | | for (var i = 0; i < parameters.Length; i++) |
| | | 26 | | { |
| | 6 | 27 | | var p = parameters[i]; |
| | | 28 | | |
| | 6 | 29 | | if (p.HasDefaultValue) |
| | | 30 | | { |
| | 4 | 31 | | args[i] = p.DefaultValue; |
| | | 32 | | } |
| | | 33 | | else |
| | | 34 | | { |
| | 2 | 35 | | args[i] = p.ParameterType.IsValueType |
| | 2 | 36 | | ? Activator.CreateInstance(p.ParameterType) |
| | 2 | 37 | | : null; |
| | | 38 | | } |
| | | 39 | | } |
| | | 40 | | |
| | 2 | 41 | | return (IActivity)ctor.Invoke(args); |
| | | 42 | | } |
| | | 43 | | } |