274
|
1 using System;
|
|
2 using System.Collections.Generic;
|
|
3 using System.Linq;
|
|
4 using Unity.Injection;
|
|
5 using Unity.Registration;
|
|
6
|
|
7 namespace Implab.ServiceHost.Unity {
|
|
8 public class TypeRegistrationBuilder : RegistrationBuilder {
|
|
9
|
|
10 readonly TypeResolver m_resolver;
|
|
11
|
|
12 readonly List<InjectionMember> m_injections = new List<InjectionMember>();
|
|
13
|
|
14 public InjectionMember[] Injections { get { return m_injections.ToArray(); } }
|
|
15
|
|
16 public Type ImplementationType {
|
|
17 get;
|
|
18 private set;
|
|
19 }
|
|
20
|
|
21 internal TypeRegistrationBuilder(TypeResolver resolver, Type registrationType, Type implementationType) : base(registrationType) {
|
|
22 ImplementationType = implementationType;
|
|
23
|
|
24 // when registering a generic mapping, register all generic parameter names as local types
|
|
25 if (ImplementationType.IsGenericTypeDefinition) {
|
|
26 m_resolver = new TypeResolver(resolver);
|
|
27
|
|
28 foreach (var p in ImplementationType.GetGenericArguments())
|
|
29 m_resolver.AddMapping(p.Name, p);
|
|
30 } else {
|
|
31 m_resolver = resolver;
|
|
32 }
|
|
33 }
|
|
34
|
|
35 internal void Visit(ConstructorInjectionElement constructorInjection) {
|
|
36
|
|
37
|
|
38 var parameters = constructorInjection.Parameters?
|
|
39 .Select(x => {
|
|
40 var valueBuilder = new InjectionValueBuilder(m_resolver, null);
|
|
41 x.Visit(valueBuilder);
|
|
42 return valueBuilder.Injection;
|
|
43 })
|
|
44 .ToArray();
|
|
45
|
|
46 var injection = parameters != null ? new InjectionConstructor(parameters) : new InjectionConstructor();
|
|
47 m_injections.Add(injection);
|
|
48 }
|
|
49
|
|
50 internal void Visit(MethodInjectionElement methodInjection) {
|
|
51 var valueContext = new InjectionValueBuilder(m_resolver, null);
|
|
52
|
|
53 var parameters = methodInjection.Parameters?
|
|
54 .Select(x => {
|
|
55 var valueBuilder = new InjectionValueBuilder(m_resolver, null);
|
|
56 x.Visit(valueBuilder);
|
|
57 return valueBuilder.Injection;
|
|
58 })
|
|
59 .ToArray();
|
|
60
|
|
61 var injection = parameters != null ? new InjectionMethod(methodInjection.Name, parameters) : new InjectionMethod(methodInjection.Name);
|
|
62 m_injections.Add(injection);
|
|
63 }
|
|
64
|
|
65 internal void Visit(PropertyInjectionElement propertyInjection) {
|
|
66 if (propertyInjection.Value == null)
|
|
67 throw new Exception($"A value value must be specified for the property '{propertyInjection.Name}'");
|
|
68
|
|
69 var propertyType = RegistrationType.GetProperty(propertyInjection.Name)?.PropertyType;
|
|
70 var valueContext = new InjectionValueBuilder(m_resolver, propertyType);
|
|
71
|
|
72 propertyInjection.Value.Visit(valueContext);
|
|
73 var injection = new InjectionProperty(propertyInjection.Name, valueContext.Injection);
|
|
74 m_injections.Add(injection);
|
|
75 }
|
|
76 }
|
|
77 } |