private InstanceProducer TryBuildCollectionInstanceProducer(Type serviceType) { Type serviceTypeDefinition = serviceType.GetGenericTypeDefinition(); if ( #if NET45 serviceTypeDefinition == typeof(IReadOnlyList <>) || serviceTypeDefinition == typeof(IReadOnlyCollection <>) || #endif serviceTypeDefinition == typeof(IList <>) || serviceTypeDefinition == typeof(ICollection <>)) { Type elementType = serviceType.GetGenericArguments()[0]; var collection = this.GetAllInstances(elementType) as IContainerControlledCollection; if (collection != null) { var registration = SingletonLifestyle.CreateSingleInstanceRegistration(serviceType, collection, this); var producer = new InstanceProducer(serviceType, registration); if (!((IEnumerable <object>)collection).Any()) { producer.IsContainerAutoRegistered = true; } return(producer); } } return(null); }
private InstanceProducer TryBuildStreamInstanceProducer(Type collectionType) { Type serviceTypeDefinition = collectionType.GetGenericTypeDefinition(); if (serviceTypeDefinition == typeof(IEnumerable <>)) { return(null); } Type elementType = collectionType.GetGenericArguments()[0]; object stream = this.GetAllInstances(elementType); if (!(stream is IContainerControlledCollection)) { return(null); } // We need special handling for Collection<T>, because the ContainerControlledCollection does not // (and can't) inherit from Collection<T>. So we have to wrap that stream into a Collection<T>. if (serviceTypeDefinition == typeof(Collection <>)) { Type listType = typeof(IList <>).MakeGenericType(elementType); stream = collectionType.GetConstructor(new[] { listType }).Invoke(new[] { stream }); } var registration = SingletonLifestyle.CreateSingleInstanceRegistration(collectionType, stream, this); return(new InstanceProducer(collectionType, registration) { IsContainerAutoRegistered = !((IEnumerable <object>)stream).Any() }); }
public void RegisterCollection <TService>(params TService[] singletons) where TService : class { Requires.IsNotNull(singletons, nameof(singletons)); Requires.DoesNotContainNullValues(singletons, nameof(singletons)); if (typeof(TService) == typeof(Type) && singletons.Any()) { throw new ArgumentException( StringResources.RegisterCollectionCalledWithTypeAsTService(singletons.Cast <Type>()), nameof(TService)); } Requires.IsNotAnAmbiguousType(typeof(TService), nameof(TService)); var singletonRegistrations = from singleton in singletons select SingletonLifestyle.CreateSingleInstanceRegistration(typeof(TService), singleton, this, singleton.GetType()); this.RegisterCollection(typeof(TService), singletonRegistrations); }