Base class for Lifetime managers - classes that control how and when instances are created by the Unity container.
Inheritance: ILifetimePolicy
Exemple #1
0
 /// <summary>
 /// Create a new instance of <see cref="RegisterEventArgs"/>.
 /// </summary>
 /// <param name="typeFrom">Type to map from.</param>
 /// <param name="typeTo">Type to map to.</param>
 /// <param name="name">Name for the registration.</param>
 /// <param name="lifetimeManager"><see cref="LifetimeManager"/> to manage instances.</param>
 public RegisterEventArgs(Type typeFrom, Type typeTo, string name, LifetimeManager lifetimeManager)
     : base(name)
 {
     this.typeFrom = typeFrom;
     this.typeTo = typeTo;
     this.lifetimeManager = lifetimeManager;
 }
 /// <summary>
 /// Create a <see cref="RegisterInstanceEventArgs"/> instance initialized with the given arguments.
 /// </summary>
 /// <param name="registeredType">Type of instance being registered.</param>
 /// <param name="instance">The instance object itself.</param>
 /// <param name="name">Name to register under, null if default registration.</param>
 /// <param name="lifetimeManager"><see cref="LifetimeManager"/> object that handles how
 /// the instance will be owned.</param>
 public RegisterInstanceEventArgs(Type registeredType, object instance, string name, LifetimeManager lifetimeManager)
     : base(name)
 {
     this.registeredType = registeredType;
     this.instance = instance;
     this.lifetimeManager = lifetimeManager;
 }
 public TypeRegistration(Type registrationType, Type mappedToType, LifetimeManager lifetimeManager, Expression factory)
 {
     this.RegistrationType = registrationType;
     this.MappedToType = mappedToType;
     this.LifetimeManager = lifetimeManager;
     this.Factory = factory;
 }
 public static void RegisterCollection(this UnityContainer container, Type serviceType, IEnumerable<Type> implementations, LifetimeManager lifetimeManager = null)
 {
     foreach (var impl in implementations)
     {
         container.RegisterType(serviceType, impl, impl.FullName, lifetimeManager ?? new TransientLifetimeManager(), new InjectionMember[0]);
     }
 }
 public DelegateLifetimeManager(
     Func<object> sourceFunc,
     LifetimeManager baseManager = null)
 {
     this._resolveDelegate = sourceFunc;
     this._baseManager = baseManager;
 }
Exemple #6
0
 public IUnityContainer RegisterInstance(Type t, string name, object instance, LifetimeManager lifetime)
 {
     ConfigActions.Add(ConfigurationActionRecord.RegisterInstanceAction(
                           t,
                           name,
                           instance,
                           lifetime));
     return this;
 }
 public IUnityContainer RegisterType(Type @from, Type to, string name, LifetimeManager lifetimeManager, params InjectionMember[] injectionMembers)
 {
     var bypassLogging = injectionMembers.Any(injectionMember => injectionMember.GetType() == typeof (BypassLoggingInjectionMember));
     if (@from == null || bypassLogging)
     {
         // we're assuming this is just a component registration in which case our logging injection, by interface, will not work.
         return _unityContainer.RegisterType(@from, to, name, lifetimeManager, injectionMembers);
     }
     return _unityContainer.RegisterType(@from, to, name, lifetimeManager, GetInjectionMembersAndLogging(injectionMembers));
 }
        /// <summary>
        ///     Register a type as all implemented interface (except those that start with <c>System</c>).
        /// </summary>
        /// <param name="container">instance</param>
        /// <param name="concrete">Class to register</param>
        /// <param name="lifetime">
        ///     The lifetime. Typically <c>HierarchicalLifetimeManager</c> (scoped),
        ///     <c>ContainerControlledLifetimeManager</c> (singleton) or <c>TransientLifetimeManager</c> (transient)
        /// </param>
        public static void Register(this IUnityContainer container, Type concrete, LifetimeManager lifetime)
        {
            // required so that all interface registrations uses the same instance.
            container.RegisterType(concrete, concrete, lifetime);

            var interfaces = concrete.GetInterfaces().Where(x => !x.Namespace.StartsWith("System"));
            foreach (var @interface in interfaces)
            {
                container.RegisterType(@interface, concrete, lifetime);
            }
        }
		private void setInstanceInterceptorFor(Type registeredType, String name, Object instance, LifetimeManager manager)
		{
			foreach (IInstanceInterceptor interceptor in interceptors.OfType<IInstanceInterceptor>())
			{
				if ((interceptor.CanIntercept(registeredType) == true) && (interceptor.GetInterceptableMethods(registeredType, instance.GetType()).Count() != 0))
				{
					this.Container.Configure<Interception>().SetInterceptorFor(registeredType, name, interceptor);
					break;
				}
			}
		}
		private void setTypeInterceptorFor(Type typeFrom, Type typeTo, String name, LifetimeManager lifetimeManager)
		{
			foreach (ITypeInterceptor interceptor in interceptors.OfType<ITypeInterceptor>())
			{
				if ((interceptor.CanIntercept(typeFrom) == true) && (interceptor.GetInterceptableMethods(typeFrom, typeTo).Count() != 0))
				{
					this.Container.Configure<Interception>().SetInterceptorFor(typeFrom, name, interceptor);
					break;
				}
			}
		}
Exemple #11
0
        public static void RegisterAutoMapperType(this IUnityContainer container, LifetimeManager lifetimeManager = null)
        {
            RegisterAutoMapperProfiles(container);

            var profiles = container.ResolveAll<Profile>();
            var autoMapperConfigurationStore = new ConfigurationStore(new TypeMapFactory(), MapperRegistry.Mappers);
            profiles.Each(autoMapperConfigurationStore.AddProfile);

            autoMapperConfigurationStore.AssertConfigurationIsValid();

            container.RegisterInstance<IConfigurationProvider>(autoMapperConfigurationStore, new ContainerControlledLifetimeManager());
            container.RegisterInstance<IConfiguration>(autoMapperConfigurationStore, new ContainerControlledLifetimeManager());

            //container.RegisterType<IMappingEngine, MappingEngine>(lifetimeManager ?? new TransientLifetimeManager(), new InjectionConstructor(typeof(IConfigurationProvider)));
            container.RegisterType<IMappingEngine, MappingEngine>(lifetimeManager ?? new TransientLifetimeManager(), new InjectionConstructor(typeof(IConfigurationProvider)), new InjectionFactory(_ => Mapper.Engine));

        }
Exemple #12
0
        public static void RegisterAutoMapperType(this IUnityContainer container, LifetimeManager lifetimeManager = null)
        {
            //Automate profiles
                RegisterAutomapperProfiles(container);

                //Collect all profiles in container and resolve them.
                var profiles = container.ResolveAll<Profile>();
                var autoMapperConfigurationStore = new ConfigurationStore(new TypeMapFactory(), MapperRegistry.Mappers);
                profiles.Each(autoMapperConfigurationStore.AddProfile);

                //Automapper Validate
                autoMapperConfigurationStore.AssertConfigurationIsValid();

                //Unity Injection
                container.RegisterInstance<IConfigurationProvider>(autoMapperConfigurationStore, new ContainerControlledLifetimeManager());
                container.RegisterInstance<IConfiguration>(autoMapperConfigurationStore, new ContainerControlledLifetimeManager());
                container.RegisterType<IMappingEngine, MappingEngine>(lifetimeManager ?? new TransientLifetimeManager(), new InjectionConstructor(typeof(IConfigurationProvider)));

                container.RegisterType<IStorage, MemoryStorage>();
                container.RegisterType<ICustomerRepository, CustomerRepository>();
        }
 private void SetLifetimeManager(Type lifetimeType, string name, LifetimeManager lifetimeManager)
 {
     if (lifetimeManager.InUse)
     {
         throw new InvalidOperationException(Resources.LifetimeManagerInUse);
     }
     if (lifetimeType.IsGenericTypeDefinition)
     {
         LifetimeManagerFactory factory =
             new LifetimeManagerFactory(Context, lifetimeManager.GetType());
         Context.Policies.Set<ILifetimeFactoryPolicy>(factory,
             new NamedTypeBuildKey(lifetimeType, name));
     }
     else
     {
         lifetimeManager.InUse = true;
         Context.Policies.Set<ILifetimePolicy>(lifetimeManager,
             new NamedTypeBuildKey(lifetimeType, name));
         if (lifetimeManager is IDisposable)
         {
             Context.Lifetime.Add(lifetimeManager);
         }
     }
 }
 public void RegisterType(Type from, Type to, LifetimeManager lifetime)
 {
     this.RegisterType(from.ToString(), to.ToString(), lifetime == null ? string.Empty : lifetime.GetType().ToString());
 }
 /// <summary>
 /// Instantiates a <see cref="Registration"/>
 /// </summary>
 /// <param name="type"></param>
 /// <param name="mapTo"></param>
 /// <param name="lifetime"></param>
 /// <param name="name"></param>
 /// <param name="injectionConstructor"></param>
 public Registration(Type type,
                     Type mapTo, 
                     LifetimeManager lifetime,
                     string name,
                     InjectionConstructor injectionConstructor = null)
 {
     _type = type;
     _mapTo = mapTo;
     _lifetime = lifetime;
     _name = name;
     _injectionConstructor = injectionConstructor;
 }
		public IUnityContainer RegisterType(Type from, Type to, string name, LifetimeManager lifetimeManager, params InjectionMember[] injectionMembers) {
			return container.RegisterType(from, to, name, lifetimeManager, injectionMembers);
		}
		public IUnityContainer RegisterInstance(Type t, string name, object instance, LifetimeManager lifetime) {
			return container.RegisterInstance(t, name, instance, lifetime);
		}
 	public IUnityContainer RegisterInstance(Type t, string name, object instance, LifetimeManager lifetime)
     {
         throw new System.NotImplementedException();
     }
Exemple #19
0
 public static ConfigurationActionRecord RegisterInstanceAction(Type t, string name, object instance, LifetimeManager lifetimeManager)
 {
     return new ConfigurationActionRecord(TestDoubles.ConfigurationMethod.RegisterInstance,
                                          t,
                                          null,
                                          name,
                                          instance,
                                          lifetimeManager);
 }
Exemple #20
0
 public ConfigurationActionRecord(ConfigurationMethod configurationMethod, Type typeFrom, Type typeTo, string name, object instance, LifetimeManager lifetime)
 {
     this.configurationMethod = configurationMethod;
     this.typeFrom = typeFrom;
     this.typeTo = typeTo;
     this.name = string.IsNullOrEmpty(name) ? null : name;
     this.instance = instance;
     this.lifetime = lifetime;
 }
Exemple #21
0
 /// <summary>
 /// RegisterType an instance with the container.
 /// </summary>
 /// <remarks>
 /// <para>
 /// Instance registration is much like setting a type as a singleton, except that instead
 /// of the container creating the instance the first time it is requested, the user
 /// creates the instance ahead of type and adds that instance to the container.
 /// </para>
 /// </remarks>
 /// <param name="t">Type of instance to register (may be an implemented interface instead of the full type).</param>
 /// <param name="instance">Object to returned.</param>
 /// <param name="name">Name for registration.</param>
 /// <param name="lifetime">
 /// <para>If true, the container will take over the lifetime of the instance,
 /// calling Dispose on it (if it's <see cref="IDisposable"/>) when the container is Disposed.</para>
 /// <para>
 ///  If false, container will not maintain a strong reference to <paramref name="instance"/>. User is reponsible
 /// for disposing instance, and for keeping the instance from being garbage collected.</para></param>
 /// <returns>The <see cref="UnityContainer"/> object that this method was called on (this in C#, Me in Visual Basic).</returns>
 public override IUnityContainer RegisterInstance(Type t, string name, object instance, LifetimeManager lifetime)
 {
     Guard.ArgumentNotNull(instance, "instance");
     Guard.ArgumentNotNull(lifetime, "lifetime");
     Guard.TypeIsAssignable(t, instance.GetType(), "instance");
     registeringInstance(this,
                         new RegisterInstanceEventArgs(t,
                                                       instance,
                                                       name,
                                                       lifetime));
     return this;
 }
 public IUnityContainer RegisterType(Type from, Type to, string name, LifetimeManager lifetimeManager, InjectionMember[] injectionMembers);
Exemple #23
0
 public static ConfigurationActionRecord RegisterAction(Type typeFrom, Type typeTo, string name, LifetimeManager lifetime)
 {
     return
         new ConfigurationActionRecord(TestDoubles.ConfigurationMethod.Register,
                                       typeFrom,
                                       typeTo,
                                       name,
                                       null,
                                       lifetime);
 }
        /// <summary>
        /// RegisterType a type mapping with the container, where the created instances will use
        /// the given <see cref="LifetimeManager"/>.
        /// </summary>
        /// <param name="from"><see cref="Type"/> that will be requested.</param>
        /// <param name="to"><see cref="Type"/> that will actually be returned.</param>
        /// <param name="name">Name to use for registration, null if a default registration.</param>
        /// <param name="lifetimeManager">The <see cref="LifetimeManager"/> that controls the lifetime
        /// of the returned instance.</param>
        /// <param name="injectionMembers">Injection configuration objects.</param>
        /// <returns>The <see cref="UnityContainer"/> object that this method was called on (this in C#, Me in Visual Basic).</returns>
        public IUnityContainer RegisterType(Type from, Type to, string name, LifetimeManager lifetimeManager, InjectionMember[] injectionMembers)
        {
            Guard.ArgumentNotNull(to, "to");
            if(string.IsNullOrEmpty(name))
            {
                name = null;
            }

            if (from != null && !from.IsGenericType && !to.IsGenericType)
            {
                Guard.TypeIsAssignable(from, to, "from");
            }

            registering(this, new RegisterEventArgs(from, to, name, lifetimeManager));

            if (injectionMembers.Length > 0)
            {
                ClearExistingBuildPlan(to, name);
                foreach(var member in injectionMembers)
                {
                    member.AddPolicies(from, to, name, policies);
                }
            }
            return this;
        }
        public IUnityContainer RegisterInstance(Type t, string name, object instance, LifetimeManager lifetime)
        {
            if (instance == null)
            {
                throw new ArgumentNullException("instance");
            }

            if (lifetime == null)
            {
                throw new ArgumentNullException("lifetime");
            }

            if (!string.IsNullOrEmpty(name))
            {
                throw new NotSupportedException("Named registrations are not supported");
            }

            this.RegisteringInstance(this, new RegisterInstanceEventArgs(t, instance, name, lifetime));

            lock (this.lockObj)
            {
                lifetime.SetValue(instance);
                this.lifetimeTable.AddOrUpdate(t, lifetime);
                this.factoryExpressionTable.AddOrUpdate(t, Expression.Constant(instance));
                this.ClearBuildPlans();
            }

            return this;
        }
        public IUnityContainer RegisterType(Type from, Type to, string name, LifetimeManager lifetimeManager, params InjectionMember[] injectionMembers)
        {
            if (to == null)
            {
                throw new ArgumentNullException("to");
            }

            if (injectionMembers == null)
            {
                throw new ArgumentNullException("injectionMembers");
            }

            if ((from != null && from.GetTypeInfo().IsGenericTypeDefinition) || to.GetTypeInfo().IsGenericTypeDefinition)
            {
                throw new ArgumentException("Open Generic Types are not supported");
            }

            if (!string.IsNullOrEmpty(name))
            {
                throw new NotSupportedException("Named registrations are not supported");
            }

            if (injectionMembers.Length > 1)
            {
                throw new NotSupportedException("Multiple injection members are not supported");
            }

            Logger.RegisterType(from ?? to, to, lifetimeManager);
            this.Registering(this, new RegisterEventArgs(from, to, name, lifetimeManager));

            lock (this.lockObj)
            {
                if (from != null)
                {
                    this.typeMappingTable.AddOrUpdate(from, to);
                }

                if (lifetimeManager != null)
                {
                    this.lifetimeTable.AddOrUpdate(to, lifetimeManager);
                }

                if (injectionMembers.Length == 1)
                {
                    this.factoryExpressionTable.AddOrUpdate(to, injectionMembers[0].GenExpression(to, this));
                }

                this.ClearBuildPlans();
            }

            return this;
        }
 	public IUnityContainer RegisterType(Type from, Type to, string name, LifetimeManager lifetimeManager, params InjectionMember[] injectionMembers)
 	{
 		throw new NotImplementedException();
 	}
 public IUnityContainer RegisterInstance(Type t, string name, object instance, LifetimeManager lifetime);
Exemple #29
0
 public IUnityContainer RegisterType(Type from, Type to, string name, LifetimeManager lifetimeManager, params InjectionMember[] injectionMembers)
 {
     ConfigActions.Add(
         ConfigurationActionRecord.RegisterAction(from, to, name, lifetimeManager));
     return this;
 }
Exemple #30
0
 /// <summary>
 /// RegisterType a type mapping with the container, where the created instances will use
 /// the given <see cref="LifetimeManager"/>.
 /// </summary>
 /// <param name="from"><see cref="Type"/> that will be requested.</param>
 /// <param name="to"><see cref="Type"/> that will actually be returned.</param>
 /// <param name="name">Name to use for registration, null if a default registration.</param>
 /// <param name="lifetimeManager">The <see cref="LifetimeManager"/> that controls the lifetime
 /// of the returned instance.</param>
 /// <returns>The <see cref="UnityContainer"/> object that this method was called on (this in C#, Me in Visual Basic).</returns>
 public override IUnityContainer RegisterType(Type from, Type to, string name, LifetimeManager lifetimeManager)
 {
     if (to != null && !from.IsGenericType && !to.IsGenericType)
     {
         Guard.TypeIsAssignable(from, to, "from");
     }
     registering(this, new RegisterEventArgs(from, to, name, lifetimeManager));
     return this;
 }
 /// <summary>
 /// RegisterType an instance with the container.
 /// </summary>
 /// <remarks>
 /// <para>
 /// Instance registration is much like setting a type as a singleton, except that instead
 /// of the container creating the instance the first time it is requested, the user
 /// creates the instance ahead of type and adds that instance to the container.
 /// </para>
 /// </remarks>
 /// <param name="t">Type of instance to register (may be an implemented interface instead of the full type).</param>
 /// <param name="instance">Object to returned.</param>
 /// <param name="name">Name for registration.</param>
 /// <param name="lifetime">
 /// <para>If true, the container will take over the lifetime of the instance,
 /// calling Dispose on it (if it's <see cref="IDisposable"/>) when the container is Disposed.</para>
 /// <para>
 ///  If false, container will not maintain a strong reference to <paramref name="instance"/>. User is responsible
 /// for disposing instance, and for keeping the instance from being garbage collected.</para></param>
 /// <returns>The <see cref="UnityContainer"/> object that this method was called on (this in C#, Me in Visual Basic).</returns>
 public IUnityContainer RegisterInstance(Type t, string name, object instance, LifetimeManager lifetime)
 {
     Guard.ArgumentNotNull(instance, "instance");
     Guard.ArgumentNotNull(lifetime, "lifetime");
     Guard.InstanceIsAssignable(t, instance, "instance");
     RegisteringInstance(this,
                         new RegisterInstanceEventArgs(t,
                                                       instance,
                                                       name,
                                                       lifetime));
     return(this);
 }