Add ScriptUI to support XAML file (#320)
[platform/core/csapi/tizenfx.git] / src / Tizen.NUI / src / internal / XamlBinding / DependencyResolver.cs
1 using System;
2 using System.Linq;
3 using System.Reflection;
4 using Tizen.NUI.Binding;
5
6 namespace Tizen.NUI.Binding
7 {
8     internal static class DependencyResolver
9     {
10         static Func<Type, object[], object> Resolver { get; set; }
11
12         public static void ResolveUsing(Func<Type, object[], object> resolver)
13         {
14             Resolver = resolver;
15         }
16
17         public static void ResolveUsing(Func<Type, object> resolver)
18         {
19             Resolver = (type, objects) => resolver.Invoke(type);
20         }
21
22         internal static object Resolve(Type type, params object[] args)
23         {
24             var result = Resolver?.Invoke(type, args);
25
26             if (result != null)
27             {
28                 if (!type.IsInstanceOfType(result))
29                 {
30                     throw new InvalidCastException("Resolved instance is not of the correct type.");
31                 }
32             }
33
34             return result;
35         }
36
37         internal static object ResolveOrCreate(Type type, params object[] args)
38         {
39             var result = Resolve(type, args);
40
41             if (result != null) return result;
42
43             if (args.Length > 0)
44             {
45                 // This is by no means a general solution to matching with the correct constructor, but it'll
46                 // do for finding Android renderers which need Context (vs older custom renderers which may still use
47                 // parameterless constructors)
48                 if (type.GetTypeInfo().DeclaredConstructors.Any(info => info.GetParameters().Length == args.Length))
49                 {
50                     return Activator.CreateInstance(type, args);
51                 }
52             }
53             
54             return Activator.CreateInstance(type);
55         }
56     }
57 }