public void WhenActivationDelegateReturnsNull_ExceptionDescribesLimitType() { var target = new DelegateActivator(typeof(string), (c, p) => null); var ex = Assert.Throws<DependencyResolutionException>( () => target.ActivateInstance(new ContainerBuilder().Build(), Enumerable.Empty<Parameter>())); Assert.That(ex.Message.Contains(typeof(string).ToString())); }
public void ActivateInstance_ReturnsResultOfInvokingSuppliedDelegate() { var instance = new object(); var target = new DelegateActivator(typeof(object), (c, p) => instance); Assert.AreSame(instance, target.ActivateInstance(new ContainerBuilder().Build(), Enumerable.Empty<Parameter>())); }
/// <summary> /// Retrieve registrations for an unregistered service, to be used /// by the container. /// </summary> /// <param name="service">The service that was requested.</param> /// <param name="registrationAccessor">A function that will return existing registrations for a service.</param> /// <returns>Registrations providing the service.</returns> public IEnumerable<IComponentRegistration> RegistrationsFor(Service service, Func<Service, IEnumerable<IComponentRegistration>> registrationAccessor) { if (service == null) throw new ArgumentNullException(nameof(service)); if (registrationAccessor == null) throw new ArgumentNullException(nameof(registrationAccessor)); var swt = service as IServiceWithType; if (swt != null) { var serviceType = swt.ServiceType; Type elementType = null; if (serviceType.IsGenericEnumerableInterfaceType()) { elementType = serviceType.GetTypeInfo().GenericTypeArguments.First(); } else if (serviceType.IsArray) { elementType = serviceType.GetElementType(); } if (elementType != null) { var elementTypeService = swt.ChangeType(elementType); var elementArrayType = elementType.MakeArrayType(); var listType = typeof(List<>).MakeGenericType(elementType); var serviceTypeIsList = serviceType.IsGenericListOrCollectionInterfaceType(); var activator = new DelegateActivator( elementArrayType, (c, p) => { var elements = c.ComponentRegistry.RegistrationsFor(elementTypeService); var items = elements.Select(cr => c.ResolveComponent(cr, p)).ToArray(); var result = Array.CreateInstance(elementType, items.Length); items.CopyTo(result, 0); return serviceTypeIsList ? Activator.CreateInstance(listType, result) : result; }); var registration = new ComponentRegistration( Guid.NewGuid(), activator, new CurrentScopeLifetime(), InstanceSharing.None, InstanceOwnership.ExternallyOwned, new[] { service }, new Dictionary<string, object>()); return new IComponentRegistration[] { registration }; } } return Enumerable.Empty<IComponentRegistration>(); }