|
| 1 | +using Microsoft.Extensions.DependencyInjection; |
| 2 | +using System; |
| 3 | +using System.Collections.Generic; |
| 4 | +using System.Linq; |
| 5 | +using Unity; |
| 6 | +using Unity.Injection; |
| 7 | +using Unity.Lifetime; |
| 8 | + |
| 9 | +namespace Unity.Microsoft.DependencyInjection |
| 10 | +{ |
| 11 | + public class Aggregate |
| 12 | + { |
| 13 | + public Type Type { get; private set; } |
| 14 | + |
| 15 | + private List<ServiceDescriptor> Services { get; set; } = new List<ServiceDescriptor>(); |
| 16 | + private ServiceDescriptor Last; |
| 17 | + private IUnityContainer Container; |
| 18 | + |
| 19 | + public Aggregate(Type type, IUnityContainer container) |
| 20 | + { |
| 21 | + Type = type; |
| 22 | + Container = container; |
| 23 | + } |
| 24 | + |
| 25 | + public void AddService(ServiceDescriptor service) |
| 26 | + { |
| 27 | + Services.Add(service); |
| 28 | + Last = service; |
| 29 | + } |
| 30 | + |
| 31 | + public void Register() |
| 32 | + { |
| 33 | + foreach (var serv in Services) |
| 34 | + { |
| 35 | + var qualifier = serv.GetImplementationType().FullName; |
| 36 | + Container.Register(serv, qualifier); |
| 37 | + } |
| 38 | + |
| 39 | + Container.RegisterType(Type, Last.GetLifetime(Container), |
| 40 | + new InjectionFactory((c, t, s) => |
| 41 | + { |
| 42 | + if (Last.ServiceType.IsGenericTypeDefinition) |
| 43 | + return c.Resolve(t, Last.GetImplementationType().FullName); |
| 44 | + var instance = Resolve(c); |
| 45 | + return instance; |
| 46 | + })); |
| 47 | + |
| 48 | + var enumType = typeof(IEnumerable<>).MakeGenericType(Type); |
| 49 | + Container.RegisterType(enumType, new HierarchicalTransientLifetimeManager(Container), |
| 50 | + new InjectionFactory(c => |
| 51 | + { |
| 52 | + List<object> instances = new List<object>(); |
| 53 | + foreach (var serv in Services) |
| 54 | + { |
| 55 | + if (!serv.ServiceType.IsGenericTypeDefinition) |
| 56 | + { |
| 57 | + var qualifier = serv.GetImplementationType().FullName; |
| 58 | + var instance = Container.Resolve(serv.ServiceType, qualifier); |
| 59 | + instances.Add(instance); |
| 60 | + } |
| 61 | + } |
| 62 | + return typeof(Enumerable) |
| 63 | + .GetMethod("Cast") |
| 64 | + .MakeGenericMethod(Type) |
| 65 | + .Invoke(null, new[] { instances }); |
| 66 | + })); |
| 67 | + } |
| 68 | + |
| 69 | + public object Resolve(IUnityContainer container) |
| 70 | + { |
| 71 | + return container.Resolve(Type, Last.GetImplementationType().FullName); |
| 72 | + } |
| 73 | + } |
| 74 | +} |
0 commit comments