/// <summary>
        /// Gets a registration for some contract type.
        /// </summary>
        /// <param name="contractType">The contract type.</param>
        /// <param name="container">The container.</param>
        /// <returns><value>The registration item</value> if this source can handle it, otherwise <value>null</value>.</returns>
        public RegistrationItem GetRegistrationFor(Type contractType, IContainer container)
        {
            Type[] genericArguments = contractType.GetGenericArguments();

            // Get the Registration for the open generic type.
            RegistrationItem openGenericTypeRegistration =
                this._registrationContainer
                    .Registrations[contractType.GetGenericTypeDefinition()];

            // Register closed generic type on-the-fly.
            Type implementationType = openGenericTypeRegistration.ImplementationType.MakeGenericType(genericArguments);

            var closedGenericRegistration = new RegistrationItem(contractType)
                                                {
                                                    Activator = new ReflectionActivator(
                                                        implementationType,
                                                        container.Resolve<IConstructorSelector>(),
                                                        container.Resolve<IArgumentCollector>()
                                                        ),
                                                    ImplementationType = implementationType
                                                };

            var fluentRegistration = new FluentRegistration(closedGenericRegistration);
            fluentRegistration.ControlledBy(openGenericTypeRegistration.Lifecycle.GetType());

            return closedGenericRegistration;
        }
Exemplo n.º 2
0
        public IContainer Build()
        {
            var groupedRegistrations = registrations
                                       .GroupBy(c => c.Key.Type);

            var expandedRegistrations = new Dictionary <RegistrationKey, RegistrationItem>();

            foreach (var entry in groupedRegistrations)
            {
                if (entry.Count() == 1)
                {
                    expandedRegistrations.Add(new RegistrationKey(entry.Key), entry.LastOrDefault().Value);
                }
                if (entry.Key.IsGenericType && entry.Key.GetGenericTypeDefinition() == typeof(IEnumerable <>))
                {
                    continue;
                }
                var enumerableType = typeof(IEnumerable <>).MakeGenericType(entry.Key);
                var item           = new RegistrationItem(RegistrationTag.Enumerable, () => entry.Select(c => GetNormalizedLambda(entry.Key, c.Value)).ToArray());
                expandedRegistrations.Add(new RegistrationKey(enumerableType), item);
            }
            registrations = expandedRegistrations;

            container = new IocContainer(BuildRegistrations(), BuildKeyed());

            OnBuild?.Invoke(this, container);
            return(container);
        }
Exemplo n.º 3
0
 private Func <object> GetNormalizedLambda(Type type, RegistrationItem item)
 {
     if (item.Resolved == null)
     {
         item.Resolved = Cache(type, Normalize(type, item));
     }
     return(item.Resolved);
 }
Exemplo n.º 4
0
        public void WithGenericTransientLifecycleArgument_LifecycleIsSetToTransient()
        {
            var registrationItem   = new RegistrationItem();
            var fluentRegistration = GetRegistration(registrationItem);

            fluentRegistration.ControlledBy <TransientLifecycle>();

            registrationItem.Lifecycle.Should().BeOfType <TransientLifecycle>();
        }
Exemplo n.º 5
0
        private IocBuilder AddRegistration <TAbstract>(RegistrationTag tag, Func <object> lambda)
        {
            var type = typeof(TAbstract);

            lastItem = new RegistrationItem(tag, lambda);
            lastKey  = new RegistrationKey(type);
            registrations.Add(lastKey, lastItem);
            return(this);
        }
Exemplo n.º 6
0
        public void WithNull_GroupIsSetToNull()
        {
            var registrationItem   = new RegistrationItem(null);
            var fluentRegistration = GetRegistration(registrationItem);

            fluentRegistration.WithGroup(null);

            registrationItem.Group.Should().Be(null);
        }
Exemplo n.º 7
0
        public void WithNullAsLifecycleInstance_ArgumentExceptionThrown()
        {
            var registrationItem   = new RegistrationItem();
            var fluentRegistration = GetRegistration(registrationItem);

            Action act = () => fluentRegistration.ControlledBy((ILifecycle)null);

            act.ShouldThrow <ArgumentNullException>();
        }
        public void WithTwoArguments_AnonymousArgumentCountIsTwo()
        {
            var registrationItem   = new RegistrationItem();
            var fluentRegistration = GetRegistration(registrationItem);

            fluentRegistration.WithArguments(2, 3);

            registrationItem.Arguments.AnonymousArguments.Length.Should().Be(2);
        }
        public void WithNull_ArgumentCountStaysOnZero()
        {
            var registrationItem   = new RegistrationItem();
            var fluentRegistration = GetRegistration(registrationItem);

            fluentRegistration.WithArguments(null);

            registrationItem.Arguments.CountOfAllArguments.Should().Be(0);
        }
Exemplo n.º 10
0
        public void WithSingletonLifecycleInstanceArgument_LifecycleIsSetToSingleton()
        {
            var registrationItem   = new RegistrationItem();
            var fluentRegistration = GetRegistration(registrationItem);

            fluentRegistration.ControlledBy(new SingletonLifecycle());

            registrationItem.Lifecycle.Should().BeOfType <SingletonLifecycle>();
        }
Exemplo n.º 11
0
        public void WithObjectAsLifecycle_ArgumentExceptionThrown()
        {
            var registrationItem   = new RegistrationItem();
            var fluentRegistration = GetRegistration(registrationItem);

            Action act = () => fluentRegistration.ControlledBy(typeof(object));

            act.ShouldThrow <ArgumentException>();
        }
Exemplo n.º 12
0
        public void WithString_GroupIsSetToStringValue()
        {
            var registrationItem   = new RegistrationItem(null);
            var fluentRegistration = GetRegistration(registrationItem);
            var group = "test";

            fluentRegistration.WithGroup(group);

            registrationItem.Group.Should().Be(group);
        }
        public void WithTwoNamedAnonymousTypeArguments_TheArgumentsAreCommited()
        {
            var registrationItem   = new RegistrationItem();
            var fluentRegistration = GetRegistration(registrationItem);

            fluentRegistration.WithNamedArguments(new { Foo = "foo", Bar = new Bar() });

            registrationItem.Arguments.NamedArguments.Count.Should().Be(2);
            registrationItem.Arguments.NamedArguments["Foo"].Should().BeOfType <string>();
            registrationItem.Arguments.NamedArguments["Bar"].Should().BeOfType <Bar>();
        }
        public void WithOneFooArgument_TheArgumentIsTheSame()
        {
            var registrationItem   = new RegistrationItem();
            var fluentRegistration = GetRegistration(registrationItem);
            var foo = new Foo();

            fluentRegistration.WithArguments(foo);

            registrationItem.Arguments.AnonymousArguments.Length.Should().Be(1);
            registrationItem.Arguments.AnonymousArguments[0].Should().BeSameAs(foo);
        }
Exemplo n.º 15
0
        /// <summary>
        /// Gets a fake registration container with given registered types.
        /// </summary>
        /// <param name="typesToRegister">The types to register.</param>
        /// <returns>The registration container with registered types.</returns>
        internal static RegistrationContainer GetRegistrationContainerFor(Type[] typesToRegister)
        {
            var registrationContainer = new RegistrationContainer();

            foreach (var registeredType in typesToRegister)
            {
                var item = new RegistrationItem(registeredType);

                registrationContainer.AddRegistration(item);
            }

            return(registrationContainer);
        }
Exemplo n.º 16
0
        /// <summary>
        ///     Add all arguments to the passed registration.
        /// </summary>
        /// <param name="registrationItem">The registration.</param>
        /// <param name="arguments">The arguments.</param>
        /// <param name="namedArguments">The named arguments.</param>
        private void AddArgumentsToRegistration(RegistrationItem registrationItem, IEnumerable <object> arguments,
                                                IDictionary <string, object> namedArguments)
        {
            if (arguments != null)
            {
                registrationItem.RuntimeArguments.AddToAnonymousArguments(arguments);
            }

            if (namedArguments != null)
            {
                registrationItem.RuntimeArguments.AddToNamedArguments(namedArguments);
            }
        }
        public void WithOneNamedFooArgument_TheArgumentIsTheSame()
        {
            var registrationItem   = new RegistrationItem();
            var fluentRegistration = GetRegistration(registrationItem);
            var key = "test";
            var foo = new Foo();

            fluentRegistration.WithNamedArguments(new Dictionary <string, object> {
                { key, foo }
            });

            registrationItem.Arguments.NamedArguments.Count.Should().Be(1);
            registrationItem.Arguments.NamedArguments[key].Should().BeSameAs(foo);
        }
        /// <summary>
        /// Gets a registration for some contract type.
        /// </summary>
        /// <param name="contractType">The contract type.</param>
        /// <param name="container">The container.</param>
        /// <returns><value>The registration item</value> if this source can handle it, otherwise <value>null</value>.</returns>
        public RegistrationItem GetRegistrationFor(Type contractType, IContainer container)
        {
            Type[] genericArguments = contractType.GetGenericArguments();

            // Try get the Registration for the open generic type.
            RegistrationItem openGenericTypeRegistration = null;

            _registrationContainer.TryGetRegistration(contractType.GetGenericTypeDefinition(), out openGenericTypeRegistration);

            if (openGenericTypeRegistration == null)
            {
                throw new RegistrationNotFoundException(string.Format(Resources.RegistrationNotFoundFormat,
                                                                      contractType.GetGenericTypeDefinition()),
                                                        contractType.GetGenericTypeDefinition());
            }

            // Try to find a closed generic which passes the open signature.
            var registrationItem = _registrationContainer
                                   .GetRegistration(registration => contractType.IsAssignableFrom(registration.ImplementationType));

            Type implementationType = null;

            if (registrationItem != null)
            {
                implementationType = registrationItem.ImplementationType;
            }

            // RegisterInstance closed generic type on-the-fly, if no match until now.
            if (implementationType == null)
            {
                implementationType = openGenericTypeRegistration.ImplementationType.MakeGenericType(genericArguments);
            }

            var closedGenericRegistration = new RegistrationItem(contractType)
            {
                Activator = new ReflectionActivator(
                    implementationType,
                    container.Resolve <IConstructorSelector>(),
                    container.Resolve <IArgumentCollector>()
                    ),
                ImplementationType = implementationType
            };

            var fluentRegistration = new FluentRegistration(closedGenericRegistration);

            fluentRegistration.ControlledBy(openGenericTypeRegistration.Lifecycle.GetType());

            return(closedGenericRegistration);
        }
Exemplo n.º 19
0
        private IRegistrationBuilder AddToRegistrationBuilder(RegistrationItem registrationItem)
        {
            Action registrationCallback = () =>
            {
                if (registrationItem.Lifecycle == null)
                {
                    registrationItem.Lifecycle = new TransientLifecycle();
                }

                this._registrationContainer.AddRegistration(registrationItem);
            };

            this._registrationCallbacks.Add(registrationCallback);

            return(new RegistrationBuilder(registrationItem));
        }
Exemplo n.º 20
0
        /// <summary>
        ///     RegisterInstance the container itself for service locator reasons.
        /// </summary>
        private void RegisterContainer()
        {
            var typeOfIContainer = typeof(IContainer);

            // The container is already registered from external.
            if (_registrationContainer.HasRegistration(typeOfIContainer))
            {
                _registrationContainer.RemoveRegistration(typeOfIContainer);
            }

            var registrationItem = new RegistrationItem(typeOfIContainer)
            {
                Activator = new InstanceActivator <IContainer>(this),
                Lifecycle = new TransientLifecycle()
            };

            _registrationContainer.AddRegistration(registrationItem);
        }
Exemplo n.º 21
0
        private object Resolve(RegistrationItem registrationItem)
        {
            ResolutionContext resolutionContext = new ResolutionContext()
            {
                Container             = this,
                RegistrationContainer = this._registrationContainer,
                Arguments             = registrationItem.Arguments,
                RuntimeArguments      = registrationItem.RuntimeArguments,
                Registration          = registrationItem
            };

            object instance = registrationItem.ActivateInstance(resolutionContext);

            registrationItem.RuntimeArguments.AnonymousArguments = null;
            registrationItem.RuntimeArguments.NamedArguments     = null;

            return(instance);
        }
Exemplo n.º 22
0
        /// <summary>
        ///     Resolves a dependency internally with a registrationItem.
        /// </summary>
        /// <param name="registrationItem">The registrationItem to activate.</param>
        /// <returns>The resolved instance.</returns>
        private object Resolve(RegistrationItem registrationItem)
        {
            var resolutionContext = new ResolutionContext(
                this,
                _registrationContainer,
                registrationItem.Arguments,
                registrationItem.RuntimeArguments)
            {
                Registration = registrationItem
            };

            var instance = registrationItem.ActivateInstance(resolutionContext);

            // Clear all runtime arguments on registration.
            registrationItem.RuntimeArguments.AnonymousArguments = null;
            registrationItem.RuntimeArguments.NamedArguments     = null;

            return(instance);
        }
Exemplo n.º 23
0
        internal MisfitContainer(IRegistrationContainer registrationContainer)
        {
            this._registrationContainer = registrationContainer;

            var typeOfIContainer = typeof(IPluginContainer);

            if (this._registrationContainer.IsRegistered(typeOfIContainer))
            {
                this._registrationContainer.RemoveRegistration(typeOfIContainer);
            }

            var registrationItem = new RegistrationItem(typeOfIContainer)
            {
                Activator = new InstanceActivator <IPluginContainer>(this),
                Lifecycle = new TransientLifecycle()
            };

            this._registrationContainer.AddRegistration(registrationItem);
        }
        private ResolutionContext GetContext(Type contractType, Type implementationType)
        {
            var registrationContainer = new RegistrationContainer();

            var registration = new RegistrationItem(contractType)
            {
                Activator =
                    new LightCore.Activation.Activators.ReflectionActivator
                    (
                        implementationType,
                        new LightCore.Activation.Components.ConstructorSelector(),
                        new LightCore.Activation.Components.ArgumentCollector()
                    ),
                Lifecycle = new TransientLifecycle()
            };

            registrationContainer.AddRegistration(registration);

            return(new ResolutionContext(new Container(registrationContainer), registrationContainer));
        }
Exemplo n.º 25
0
        private Func <object> Normalize(Type type, RegistrationItem item)
        {
            if (item.RegistrationTag.HasFlag(RegistrationTag.Scope))
            {
                var lambda = item.RegistrationTag.HasFlag(RegistrationTag.Default) ? item.Lambda() : item.Lambda;
                return(new Func <object>(() =>
                {
                    if (container.ActiveContainer.resolved.ContainsKey(type))
                    {
                        return container.ActiveContainer.resolved[type].First();
                    }
                    return ((Func <object>)lambda).Invoke();
                }));
            }
            else if (item.RegistrationTag.HasFlag(RegistrationTag.Default))
            {
                return((Func <object>)item.Lambda());
            }
            else if (item.RegistrationTag.HasFlag(RegistrationTag.Lambda))
            {
                return(item.Lambda);
            }
            else if (item.RegistrationTag.HasFlag(RegistrationTag.Singleton))
            {
                var resolve = (Func <object>)item.Lambda();
                var lazy    = new Lazy <object>(resolve);
                return(new Func <object>(() => lazy.Value));
            }
            else if (item.RegistrationTag.HasFlag(RegistrationTag.Enumerable))
            {
                var dynamicCast = typeof(Enumerable).GetMethod("Cast").MakeGenericMethod(new[] { type.GetGenericArguments().First() });
                var lambda      = (IEnumerable <Func <object> >)item.Lambda();

                return(() => dynamicCast.Invoke(null, new[] { lambda.Select(c => c.Invoke()).ToArray() }));
            }
            else
            {
                return(() => item.Lambda());
            }
        }
Exemplo n.º 26
0
        /// <summary>
        /// Add a registrationItem to the registrations.
        /// </summary>
        /// <param name="registrationItem">The registration to add.</param>
        private IFluentRegistration AddToRegistrationFluent(RegistrationItem registrationItem)
        {
            Action registrationCallback = () =>
            {
                // Set default reuse scope, if not user defined. (System default is <see cref="TransientLifecycle" />.
                if (registrationItem.Lifecycle == null)
                {
                    registrationItem.Lifecycle = this._defaultLifecycleFunction();
                }

                if (_activeRegistrationGroupsInternal != null &&
                    registrationItem.Group != null)
                {
                    if (
                        !this._activeRegistrationGroupsInternal.Any(
                            g => g.Trim() == registrationItem.Group.Trim()))
                    {
                        // Do not add inactive registrationItem.
                        return;
                    }
                }

                if (_activeRegistrationGroupsInternal == null && registrationItem.Group != null)
                {
                    // Do not add inactive registrationItem.
                    return;
                }

                _registrationContainer.AddRegistration(registrationItem);
            };

            _registrationCallbacks.Add(registrationCallback);

            // Return a new instance of <see cref="IFluentRegistration" /> for supporting a fluent interface for registration configuration.
            return(new FluentRegistration(registrationItem));
        }
        /// <summary>
        /// Gets a registration for some contract type.
        /// </summary>
        /// <param name="contractType">The contract type.</param>
        /// <param name="container">The container.</param>
        /// <returns><value>The registration item</value> if this source can handle it, otherwise <value>null</value>.</returns>
        public RegistrationItem GetRegistrationFor(Type contractType, IContainer container)
        {
            Type[] genericArguments = contractType.GetGenericArguments();

            // Try get the Registration for the open generic type.
            RegistrationItem openGenericTypeRegistration = null;
            this._registrationContainer.TryGetRegistration(contractType.GetGenericTypeDefinition(), out openGenericTypeRegistration);

            if (openGenericTypeRegistration == null)
            {
                throw new RegistrationNotFoundException(string.Format(Resources.RegistrationNotFoundFormat,
                                                                      contractType.GetGenericTypeDefinition()),
                                                                      contractType.GetGenericTypeDefinition());
            }

            // Try to find a closed generic which passes the open signature.
            var registrationItem = this._registrationContainer
                .GetRegistration(registration => contractType.IsAssignableFrom(registration.ImplementationType));

            Type implementationType = null;

            if (registrationItem != null)
            {
                implementationType = registrationItem.ImplementationType;
            }

            // Register closed generic type on-the-fly, if no match until now.
            if (implementationType == null)
            {
                implementationType = openGenericTypeRegistration.ImplementationType.MakeGenericType(genericArguments);
            }

            var closedGenericRegistration = new RegistrationItem(contractType)
                                                {
                                                    Activator = new ReflectionActivator(
                                                        implementationType,
                                                        container.Resolve<IConstructorSelector>(),
                                                        container.Resolve<IArgumentCollector>()
                                                        ),
                                                    ImplementationType = implementationType
                                                };

            var fluentRegistration = new FluentRegistration(closedGenericRegistration);
            fluentRegistration.ControlledBy(openGenericTypeRegistration.Lifecycle.GetType());

            return closedGenericRegistration;
        }
Exemplo n.º 28
0
 /// <summary>
 /// Initializes a new instance of <see cref="FluentRegistration" /> type.
 /// </summary>
 /// <param name="registrationItem">The current mapping item.</param>
 internal FluentRegistration(RegistrationItem registrationItem)
 {
     this._registrationItem = registrationItem;
 }
Exemplo n.º 29
0
        public static Task<int> RegisterNewUserTask(RegistrationItem vm)
        {
            var client = WebService.Instance.WS;
            var tcs = new TaskCompletionSource<int>();

            EventHandler<RegisterNewUserCompletedEventArgs> handler = null;
            handler = (sender, e) =>
            {
                client.RegisterNewUserCompleted -= handler;

                if (e.Error != null)
                {
                    tcs.SetException(e.Error);
                }
                else
                {
                    tcs.SetResult(e.Result);
                }
            };

            client.RegisterNewUserCompleted += handler;
            client.RegisterNewUserAsync(vm);

            return tcs.Task;
        }
Exemplo n.º 30
0
 internal IFluentRegistration GetRegistration(RegistrationItem registrationItem)
 {
     return(new LightCore.Fluent.FluentRegistration(registrationItem));
 }