Esempio n. 1
0
        /// <inheritdoc />
        public IUnityContainer RegisterFactory(Type type, string name, Func <IUnityContainer, Type, string, object> factory, IFactoryLifetimeManager lifetimeManager)
        {
            // Validate input
            if (null == type)
            {
                throw new ArgumentNullException(nameof(type));
            }
            if (null == factory)
            {
                throw new ArgumentNullException(nameof(factory));
            }
            if (null == lifetimeManager)
            {
                lifetimeManager = TransientLifetimeManager.Instance;
            }
            if (((LifetimeManager)lifetimeManager).InUse)
            {
                throw new InvalidOperationException(LifetimeManagerInUse);
            }

            // Create registration and add to appropriate storage
            var container = lifetimeManager is SingletonLifetimeManager ? _root : this;

#pragma warning disable CS0618 // TODO: InjectionFactory
            var injectionFactory = new InjectionFactory(factory);
#pragma warning restore CS0618
            var injectionMembers = new InjectionMember[] { injectionFactory };
            var registration     = new ContainerRegistration(_validators, type, ((LifetimeManager)lifetimeManager), injectionMembers);

            // Add or replace existing
            var previous = container.Register(type, name, registration);
            if (previous is ContainerRegistration old &&
                old.LifetimeManager is IDisposable disposable)
            {
                // Dispose replaced lifetime manager
                container.LifetimeContainer.Remove(disposable);
                disposable.Dispose();
            }

            // If Disposable add to container's lifetime
            if (lifetimeManager is IDisposable manager)
            {
                container.LifetimeContainer.Add(manager);
            }

            // Add Injection Members
            injectionFactory.AddPolicies <BuilderContext, ContainerRegistration>(
                type, type, name, ref registration);

            // Check what strategies to run
            registration.BuildChain = _strategiesChain.ToArray()
                                      .Where(strategy => strategy.RequiredToBuildType(this,
                                                                                      type, registration, injectionMembers))
                                      .ToArray();
            // Raise event
            container.Registering?.Invoke(this, new RegisterEventArgs(type, type, name,
                                                                      ((LifetimeManager)lifetimeManager)));
            return(this);
        }
Esempio n. 2
0
        public static string GetMappingAsString(this ContainerRegistration registration)
        {
            var regType = ToString(registration.RegisteredType);

            var mapTo = ToString(registration.MappedToType);

            mapTo = mapTo != regType ? " -> " + mapTo : string.Empty;

            var regName = registration.Name ?? "[default]";

            var lifetime = registration.LifetimeManagerType.Name;

            lifetime = lifetime.Substring(0, lifetime.Length - "LifetimeManager".Length);

            return(string.Format("+ {0}{1} '{2}' {3}", regType, mapTo, regName, lifetime));
        }
        /// <inheritdoc />
        IUnityContainer IUnityContainer.RegisterType(Type typeFrom, Type typeTo, string name, ITypeLifetimeManager lifetimeManager, InjectionMember[] injectionMembers)
        {
            var mappedToType   = typeTo;
            var registeredType = typeFrom ?? typeTo;

            if (null == registeredType)
            {
                throw new ArgumentNullException(nameof(typeTo));
            }

            // Validate if they are assignable
            TypeValidator?.Invoke(typeFrom, typeTo);

            try
            {
                LifetimeManager manager = (null != lifetimeManager)
                                        ? (LifetimeManager)lifetimeManager
                                        : TypeLifetimeManager.CreateLifetimePolicy();
                if (manager.InUse)
                {
                    throw new InvalidOperationException(LifetimeManagerInUse);
                }

                // Create registration and add to appropriate storage
                var container    = manager is SingletonLifetimeManager ? _root : this;
                var registration = new ContainerRegistration(_validators, typeTo, manager, injectionMembers);
                if (manager is ContainerControlledLifetimeManager lifeteime)
                {
                    lifeteime.Scope = container;
                }

                // Add or replace existing
                var previous = container.Register(registeredType, name, registration);
                if (previous is ContainerRegistration old &&
                    old.LifetimeManager is IDisposable disposable)
                {
                    // Dispose replaced lifetime manager
                    container.LifetimeContainer.Remove(disposable);
                    disposable.Dispose();
                }

                // If Disposable add to container's lifetime
                if (manager is IDisposable disposableManager)
                {
                    container.LifetimeContainer.Add(disposableManager);
                }

                // Add Injection Members
                if (null != injectionMembers && injectionMembers.Length > 0)
                {
                    foreach (var member in injectionMembers)
                    {
                        member.AddPolicies <BuilderContext, ContainerRegistration>(
                            registeredType, mappedToType, name, ref registration);
                    }
                }

                // Check what strategies to run
                registration.BuildChain = _strategiesChain.ToArray()
                                          .Where(strategy => strategy.RequiredToBuildType(this,
                                                                                          registeredType, registration, injectionMembers))
                                          .ToArray();
                // Raise event
                container.Registering?.Invoke(this, new RegisterEventArgs(registeredType,
                                                                          mappedToType,
                                                                          name,
                                                                          manager));
            }
            catch (Exception ex)
            {
                var builder = new StringBuilder();

                builder.AppendLine(ex.Message);
                builder.AppendLine();

                var parts    = new List <string>();
                var generics = null == typeFrom ? typeTo?.Name : $"{typeFrom?.Name},{typeTo?.Name}";
                if (null != name)
                {
                    parts.Add($" '{name}'");
                }
                if (null != lifetimeManager && !(lifetimeManager is TransientLifetimeManager))
                {
                    parts.Add(lifetimeManager.ToString());
                }
                if (null != injectionMembers && 0 != injectionMembers.Length)
                {
                    parts.Add(string.Join(" ,", injectionMembers.Select(m => m.ToString())));
                }

                builder.AppendLine($"  Error in:  RegisterType<{generics}>({string.Join(", ", parts)})");
                throw new InvalidOperationException(builder.ToString(), ex);
            }

            return(this);
        }
        /// <inheritdoc />
        IUnityContainer IUnityContainer.RegisterInstance(Type type, string name, object instance, IInstanceLifetimeManager lifetimeManager)
        {
            var             mappedToType = instance?.GetType();
            var             typeFrom     = type ?? mappedToType;
            LifetimeManager manager      = (null != lifetimeManager)
                                    ? (LifetimeManager)lifetimeManager
                                    : InstanceLifetimeManager.CreateLifetimePolicy();

            try
            {
                // Validate input
                if (null == typeFrom)
                {
                    throw new InvalidOperationException($"At least one of Type arguments '{nameof(type)}' or '{nameof(instance)}' must be not 'null'");
                }

                if (manager.InUse)
                {
                    throw new InvalidOperationException(LifetimeManagerInUse);
                }
                manager.SetValue(instance, LifetimeContainer);

                // Create registration and add to appropriate storage
                var container    = manager is SingletonLifetimeManager ? _root : this;
                var registration = new ContainerRegistration(null, mappedToType, manager);
                if (manager is ContainerControlledLifetimeManager lifeteime)
                {
                    lifeteime.Scope = container;
                }

                // Add or replace existing
                var previous = container.Register(typeFrom, name, registration);
                if (previous is ContainerRegistration old &&
                    old.LifetimeManager is IDisposable disposable)
                {
                    // Dispose replaced lifetime manager
                    container.LifetimeContainer.Remove(disposable);
                    disposable.Dispose();
                }

                // If Disposable add to container's lifetime
                if (manager is IDisposable disposableManager)
                {
                    container.LifetimeContainer.Add(disposableManager);
                }

                // Check what strategies to run
                registration.BuildChain = _strategiesChain.ToArray()
                                          .Where(strategy => strategy.RequiredToResolveInstance(this, registration))
                                          .ToArray();
                // Raise event
                container.RegisteringInstance?.Invoke(this, new RegisterInstanceEventArgs(typeFrom, instance,
                                                                                          name, manager));
            }
            catch (Exception ex)
            {
                var parts = new List <string>();

                if (null != name)
                {
                    parts.Add($" '{name}'");
                }
                if (null != lifetimeManager && !(lifetimeManager is TransientLifetimeManager))
                {
                    parts.Add(lifetimeManager.ToString());
                }

                var message = $"Error in  RegisterInstance<{typeFrom?.Name}>({string.Join(", ", parts)})";
                throw new InvalidOperationException(message, ex);
            }

            return(this);
        }
 /// <summary>
 /// Resolve an instance of the default requested type from the container.
 /// </summary>
 /// <param name="container">Container to resolve from.</param>
 /// <param name="registration">Registration to be resolved.</param>
 public static object Resolve(this IUnityContainer container, ContainerRegistration registration)
 {
     Guard.ArgumentNotNull(container, "container");
     Guard.ArgumentNotNull(container, "registration");
     return(container.Resolve(registration.RegisteredType, registration.Name));
 }