/// <summary>
        /// Called during the chain of responsibility for a build operation. The
        /// PreBuildUp method is called when the chain is being executed in the
        /// forward direction.
        /// </summary>
        /// <param name="context">Context of the build operation.</param>
        public override void PreBuildUp(IBuilderContext context)
        {
            // If type is registered in the Unity container, don't even bother messing with MEF
            var policy = context.Policies.Get <IBuildKeyMappingPolicy>(context.OriginalBuildKey);

            if (policy != null)
            {
                return;
            }

            var container  = context.Policies.Get <ICompositionContainerPolicy>(null).Container;
            var buildKey   = context.BuildKey;
            var lazyExport = ContainerServices.Resolve(container, buildKey.Type, buildKey.Name);

            if (lazyExport != null)
            {
                if (context.BuildKey.Type.IsGenericType && context.BuildKey.Type.GetGenericTypeDefinition() == typeof(Lazy <,>))
                {
                    context.Existing = lazyExport;
                }
                else
                {
                    context.Existing      = lazyExport.Value;
                    context.BuildComplete = true;
                }
            }
        }
Esempio n. 2
0
 public ChildContainerOptions(bool detachRegistrationMappingsFromParentContainer,
                              bool detachResolveDelegatesFromParentContainer = false,
                              ContainerServices newContainerServices         = null)
 {
     DetachRegistrationMappingsFromParentContainer = detachRegistrationMappingsFromParentContainer;
     DetachResolveDelegatesFromParentContainer     = detachRegistrationMappingsFromParentContainer || detachResolveDelegatesFromParentContainer;
     NewContainerServices = newContainerServices;
 }
        private DependencyInjectionContainer(DependencyInjectionContainer parentContainer, ChildContainerOptions childContainerOptions)
        {
            Services = childContainerOptions.NewContainerServices ?? parentContainer.Services;
            _registrationMappings = childContainerOptions.DetachRegistrationMappingsFromParentContainer ? CreateCloneOfRegistrationMappings(parentContainer._registrationMappings) : parentContainer._registrationMappings;

            _resolveDelegates = childContainerOptions.DetachResolveDelegatesFromParentContainer ? Services.ConcurrentDictionaryFactory.Create <ResolveDelegateId, ResolveDelegate>() : parentContainer._resolveDelegates;
            Scope             = Services.ContainerScopeFactory.CreateScope(parentContainer.Scope);
        }
        public DependencyInjectionContainer(ContainerServices services = null)
        {
            Services = services ?? ContainerServices.DefaultServices;
            Scope    = Services.ContainerScopeFactory.CreateScope();
            _registrationMappings = Services.ConcurrentDictionaryFactory.Create <Type, IConcurrentList <Registration> >();
            _resolveDelegates     = Services.ConcurrentDictionaryFactory.Create <ResolveDelegateId, ResolveDelegate>();

            Scope.TryAddDisposable(_registrationMappings);
            Scope.TryAddDisposable(_resolveDelegates);
            Services.SetupContainer?.Invoke(this);
        }
        private static object ResolveEnumerable <T>(IBuilderContext context)
        {
            var container   = context.NewBuildUp <IUnityContainer>();
            var typeToBuild = typeof(T);
            var results     = ResolveAll(container, typeToBuild, typeToBuild).OfType <T>().ToList();

            // Add parts from the MEF
            var containerPolicy = context.Policies.Get <ICompositionContainerPolicy>(null);

            if (containerPolicy != null)
            {
                var parts = ContainerServices.ResolveAll(
                    containerPolicy.Container,
                    typeToBuild,
                    null);

                results.AddRange(parts.Select(part => (T)part.Value));
            }

            return(results);
        }
Esempio n. 6
0
        private static object ResolveLazyWithMetadataEnumerable <T, TMetadata>(IBuilderContext context)
        {
            var container   = context.NewBuildUp <IUnityContainer>();
            var typeToBuild = typeof(T);
            var typeWrapper = typeof(Lazy <T, TMetadata>);
            var results     = ResolveAll(container, typeToBuild, typeWrapper).OfType <Lazy <T, TMetadata> >().ToList();

            // Add parts from the MEF
            var containerPolicy = context.Policies.Get <ICompositionContainerPolicy>(null);

            if (containerPolicy != null)
            {
                var parts = ContainerServices.ResolveAllWithMetadata <TMetadata>(
                    containerPolicy.Container,
                    typeToBuild,
                    null);

                results.AddRange(parts.Select(innerPart => new Lazy <T, TMetadata>(() => (T)innerPart.Value, (TMetadata)innerPart.Metadata)));
            }

            return(results);
        }
 /// <exception cref="System.Exception"></exception>
 protected virtual void WithClient(IContainerBlock block)
 {
     ContainerServices.WithContainer(OpenClient(), block);
 }
 public ConfigureCoreServices(ContainerServices container_services)
 {
     this.container_services = container_services;
 }
Esempio n. 9
0
        /// <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>
        /// <remarks>
        ///   If the source is queried for service s, and it returns a component that implements both s and s', then it
        ///   will not be queried again for either s or s'. This means that if the source can return other implementations
        ///   of s', it should return these, plus the transitive closure of other components implementing their
        ///   additional services, along with the implementation of s. It is not an error to return components
        ///   that do not implement <paramref name = "service" />.
        /// </remarks>
        IEnumerable <IComponentRegistration> IRegistrationSource.RegistrationsFor(Service service,
                                                                                  Func
                                                                                  <Service,
                                                                                   IEnumerable <IComponentRegistration>
                                                                                  > registrationAccessor)
        {
            var typedService = service as IServiceWithType;

            // If the requested service is not a typed service or if any non-MEF registrations exist for the service, don't bother going to MEF.
            if (typedService == null /*|| registrationAccessor(service).Any()*/)
            {
                yield break;
            }
            var serviceType = typedService.ServiceType;
            // Handling the enumerable scenario here but really it should be handled by the CollectionRegistrationSource,
            // but just in case the it was excluded from the container...
            Type elementType = null;

            if (serviceType.IsGenericTypeDefinedBy(typeof(IEnumerable <>)))
            {
                elementType = serviceType.GetGenericArguments()[0];
            }
            else if (serviceType.IsArray)
            {
                elementType = serviceType.GetElementType();
            }
            var keyedService = typedService as KeyedService;
            var serviceName  = keyedService != null?keyedService.ServiceKey.ToString() : null;

            var lazyExports = ContainerServices.ResolveAll(Container, elementType ?? serviceType, serviceName);

            if (elementType != null)
            {
                yield return
                    (RegistrationBuilder.ForDelegate(elementType.MakeArrayType(),
                                                     (c, p) =>
                {
                    var instances =
                        lazyExports.Select(export => export.Value).ToArray();
                    var array = Array.CreateInstance(elementType,
                                                     instances.Length);
                    instances.CopyTo(array, 0);
                    return array;
                })
                     .ExternallyOwned()
                     .WithMetadata("Source", "MEF")
                     .CreateRegistration());
            }
            else
            {
                foreach (var lazyExport in lazyExports)
                {
                    var export = lazyExport;
                    yield return(RegistrationBuilder.ForDelegate(serviceType, (c, p) => export.Value)
                                 .PreserveExistingDefaults()
                                 .ExternallyOwned()
                                 .WithMetadata("Source", "MEF")
                                 .As(service)
                                 .CreateRegistration());
                }
            }
        }
Esempio n. 10
0
        /// <summary>
        /// Resolves an instance of the Test Subject from the Current IoC Container.
        /// </summary>
        /// <returns></returns>
        protected virtual TTestSubject ResolveTestSubjectInstance()
        {
            var instance = ContainerServices.CurrentContainer().Resolve <TTestSubject>();

            return(instance);
        }