コード例 #1
0
        public void AfterCreating_type_matching_is_precise()
        {
            var container = new PocketContainer()
                            .Register <IList <string> >(c => new List <string>())
                            .Register <List <string> >(c => new List <string>())
                            .AfterCreating <List <string> >(l =>
            {
                l.Add("List");
            })
                            .AfterCreating <IList <string> >(l =>
            {
                l.Add("IList");
            });

            var ilist = container.Resolve <IList <string> >();
            var list  = container.Resolve <List <string> >();

            ilist.Should()
            .HaveCount(1)
            .And
            .OnlyContain(item => item == "IList");

            list.Should()
            .HaveCount(1)
            .And
            .OnlyContain(item => item == "List");
        }
コード例 #2
0
        public void Strategies_can_be_chained()
        {
            var container = new PocketContainer()
                            .AddStrategy(t =>
            {
                if (t == typeof(IEnumerable <int>))
                {
                    return(c => new[] { 1, 2, 3 });
                }
                return(null);
            })
                            .AddStrategy(t =>
            {
                if (t == typeof(IEnumerable <string>))
                {
                    return(c => new[] { "1", "2", "3" });
                }
                return(null);
            });

            container.Resolve <IEnumerable <int> >()
            .Should()
            .BeEquivalentTo(new[] { 1, 2, 3 });
            container.Resolve <IEnumerable <string> >()
            .Should()
            .BeEquivalentTo("1", "2", "3");
        }
コード例 #3
0
        public void Default_construction_strategy_can_be_overridden_example_1_implicit_IEnumerable_support()
        {
            var container = new PocketContainer()
                            .Register(c => "good day!")
                            .Register(c => 456);

            // when someone asks for an IEnumerable<T> give back a List<T> containing the registered value
            container.AddStrategy(type =>
            {
                if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IEnumerable <>))
                {
                    return(c =>
                    {
                        var singleInstanceType = type.GetGenericArguments().Single();
                        var listType = typeof(List <>).MakeGenericType(singleInstanceType);
                        var list = Activator.CreateInstance(listType);
                        var resolved = c.Resolve(singleInstanceType);
                        ((dynamic)list).Add((dynamic)resolved);
                        return list;
                    });
                }
                return(null);
            });

            var strings = container.Resolve <IEnumerable <string> >();
            var ints    = container.Resolve <IEnumerable <int> >();

            Console.WriteLine(strings);
            Console.WriteLine(ints);

            ints.Single().Should().Be(456);
            strings.Single().Should().Be("good day!");
        }
コード例 #4
0
        public void RegisterSingle_can_be_used_to_register_the_same_instance_for_the_lifetime_of_the_container()
        {
            var container = new PocketContainer()
                            .RegisterSingle(c => new HasDefaultCtor());

            var one = container.Resolve <HasDefaultCtor>();
            var two = container.Resolve <HasDefaultCtor>();

            one.Should().BeSameAs(two);
        }
コード例 #5
0
        public void Recursive_resolve_of_singleton_instances_does_not_stack_overflow_when_the_resolved_type_has_a_parameterless_constructor()
        {
            var container = new PocketContainer()
                            .RegisterSingle(c => c.Resolve <IAmAGenericImplementation <string> >());

            var first  = container.Resolve <IAmAGenericImplementation <string> >();
            var second = container.Resolve <IAmAGenericImplementation <string> >();

            first.Should().BeSameAs(second).And.NotBeNull();
        }
コード例 #6
0
        public void RegisterSingle_non_generic_can_be_used_to_register_the_same_instance_for_the_lifetime_of_the_container()
        {
            var container = new PocketContainer()
                            .RegisterSingle(typeof(HasOneParamCtor <int>), c => new HasOneParamCtor <int>(new Random().Next()));

            var one = container.Resolve <HasOneParamCtor <int> >();
            var two = container.Resolve <HasOneParamCtor <int> >();

            one.Should().BeSameAs(two);
            one.Value1.Should().Be(two.Value1);
        }
コード例 #7
0
        public void AfterCreating_on_transient_registration_does_not_result_in_singleton_registration()
        {
            var container = new PocketContainer()
                            .Register(c => new List <string>())
                            .AfterCreating <List <string> >(list => list.Add("hi"));

            var resolved1 = container.Resolve <List <string> >();
            var resolved2 = container.Resolve <List <string> >();

            resolved2.Should().NotBeSameAs(resolved1);
        }
コード例 #8
0
        public void When_used_with_RegisterSingleton_then_AfterCreating_can_be_used_to_replace_the_returned_instance_when_resolved_using_non_generic_Resolve()
        {
            var container = new PocketContainer()
                            .RegisterSingle(c => new HasOneParamCtor <string>("before"))
                            .AfterCreating <HasOneParamCtor <string> >(instance => new HasOneParamCtor <string>("after"));

            var resolved1 = container.Resolve(typeof(HasOneParamCtor <string>)) as HasOneParamCtor <string>;
            var resolved2 = container.Resolve(typeof(HasOneParamCtor <string>)) as HasOneParamCtor <string>;

            resolved1.Value1.Should().Be("after");
            resolved2.Should().BeSameAs(resolved1);
        }
コード例 #9
0
        public void RegisterSingle_returns_only_single_instances_when_dependent_and_dependency_are_both_registered_as_single()
        {
            var container = new PocketContainer()
                            .RegisterSingle(c => new HasDefaultCtor())
                            .RegisterSingle(c => new HasOneParamCtor <HasDefaultCtor>(c.Resolve <HasDefaultCtor>()));

            var one = container.Resolve <HasOneParamCtor <HasDefaultCtor> >();
            var two = container.Resolve <HasOneParamCtor <HasDefaultCtor> >();

            one.Should().BeSameAs(two);
            one.Value1.Should().BeSameAs(two.Value1);
        }
コード例 #10
0
        public void RegisterSingle_can_overwrite_previous_RegisterSingle()
        {
            var container = new PocketContainer();

            container.RegisterSingle <IAmAnInterface>(c => new HasDefaultCtor());

            container.Resolve <IAmAnInterface>().Should().BeOfType <HasDefaultCtor>();

            container.RegisterSingle <IAmAnInterface>(c => new HasOneParamCtor <string>("second registration"));

            container.Resolve <IAmAnInterface>().Should().BeOfType <HasOneParamCtor <string> >();
        }
コード例 #11
0
        public void A_type_can_be_resolved_as_optional_first_and_later_as_non_optional()
        {
            var container = new PocketContainer();

            var optional = container.Resolve <HasOneOptionalParameterCtor <IAmAnInterface> >();

            optional.Value.Should().BeNull();

            Action resolveNotOptional = () => container.Resolve <HasOneParamCtor <IAmAnInterface> >();

            resolveNotOptional.ShouldThrow <ArgumentException>();
        }
コード例 #12
0
        public void Recursive_resolve_of_transient_instances_does_not_stack_overflow_when_the_resolved_type_has_a_parameterless_constructor()
        {
            var container = new PocketContainer()
                            .Register(c => c.Resolve <IAmAGenericImplementation <string> >());

            var direct = container.Resolve <IAmAGenericImplementation <string> >();

            direct.Should().NotBeNull();

            var indirect = container.Resolve <HasOneParamCtor <IAmAGenericImplementation <string> > >();

            indirect.Value1.Should().NotBeNull();
        }
コード例 #13
0
        public void A_strategy_can_be_added_and_specified_to_be_called_after_existing_strategies()
        {
            var container = new PocketContainer()
                            .AddStrategy(t => t == typeof(IList <string>)
                                      ? c => new[] { "first" }.ToList()
                                      : (Func <PocketContainer, object>)null)
                            // adding the less specific strategy second
                            .AddStrategy(t => t == typeof(IEnumerable <string>)
                                      ? c => new[] { "second" }
                                      : (Func <PocketContainer, object>)null,
                                         executeFirst: false);

            container.Resolve <IEnumerable <string> >().Should().Contain("second");
            container.Resolve <IList <string> >().Should().Contain("first");
        }
コード例 #14
0
        public void Multiple_AfterResolve_functions_can_be_applied()
        {
            var container = new PocketContainer()
                            .Register(c =>
            {
                var hashSet = new HashSet <string> {
                    "initial"
                };
                return(hashSet);
            })
                            .AfterResolve <HashSet <string> >((c, hashSet) =>
            {
                hashSet.Add("one");
                return(hashSet);
            })
                            .AfterResolve <HashSet <string> >((c, hashSet) =>
            {
                hashSet.Add("two");
                return(hashSet);
            });

            var set = container.Resolve <HashSet <string> >();

            set.Should().BeEquivalentTo(new object[] { "initial", "one", "two" });
        }
コード例 #15
0
        public void UseDependencies_can_be_used_to_set_dependencies_using_an_application_owned_container()
        {
            var applicationsContainer = new PocketContainer()
                                        .Register <IPaymentService>(_ => new CreditCardPaymentGateway(chargeLimit: 1));

            Configuration.Current
            .UseDependencies(type =>
            {
                if (applicationsContainer.Any(reg => reg.Key == type))
                {
                    return(() => applicationsContainer.Resolve(type));
                }

                return(null);
            });

            var order = new Order(new CreateOrder(Any.FullName()))
                        .Apply(new AddItem
            {
                Price       = 5m,
                ProductName = Any.Word()
            })
                        .Apply(new Ship())
                        .Apply(new ChargeAccount
            {
                AccountNumber = Any.PositiveInt().ToString()
            });

            order.Events()
            .Last()
            .Should()
            .BeOfType <Order.PaymentConfirmed>();
        }
コード例 #16
0
        public async Task AfterCreating_is_threadsafe()
        {
            var container = new PocketContainer()
                            .Register <IList <string> >(c => new List <string>());

            var barrier = new Barrier(2);

            var task1 = Task.Run(() =>
            {
                barrier.SignalAndWait();
                container.AfterCreating <IList <string> >(list =>
                {
                    list.Add("one");
                });
            });

            var task2 = Task.Run(() =>
            {
                barrier.SignalAndWait();
                container.AfterCreating <IList <string> >(list =>
                {
                    list.Add("two");
                });
            });

            await Task.WhenAll(task1, task2);

            container.Resolve <IList <string> >()
            .Should()
            .Contain("one")
            .And
            .Contain("two");
        }
コード例 #17
0
        internal static void TrySubscribeDiscoveredHandler <T>(
            Configuration configuration,
            Type commandType,
            PocketContainer c,
            ICommandReceiver <T> receiver)
        {
            foreach (var handlerDescription in
                     configuration.CommandHandlerDescriptions
                     .Where(t => t.HandledCommandType == commandType))
            {
                var handler = c.Resolve(handlerDescription.HandlerInterface) as ICommandHandler <T>;

                if (configuration.Properties.TracingEnabled)
                {
                    handler = handler.Trace();
                }

                var subscription = receiver.Subscribe(handler);

                configuration.RegisterForDisposal(subscription);

                Logger <Configuration> .Log.Trace(
                    "Subscribing discovered command handler: {handler} to handle commands of type {commandType}",
                    handlerDescription.ConcreteHandlerType,
                    handlerDescription.HandledCommandType);
            }
        }
コード例 #18
0
        public void Can_resolve_via_a_registered_untyped_factory_function()
        {
            var s         = Guid.NewGuid().ToString();
            var container = new PocketContainer().Register(typeof(string), c => s);

            container.Resolve <string>().Should().Be(s);
        }
        public void Top_level_types_resolved_from_the_dependency_resolver()
        {
            var resolver  = new FakeDependencyResolver(t => "hola!");
            var container = new PocketContainer().IncludeDependencyResolver(resolver);

            container.Resolve <string>().Should().Be("hola!");
        }
        public void Top_level_types_resolved_from_the_dependency_resolver()
        {
            var resolver = new FakeDependencyResolver(t => "hola!");
            var container = new PocketContainer().IncludeDependencyResolver(resolver);

            container.Resolve<string>().Should().Be("hola!");
        }
コード例 #21
0
        public void AfterResolve_is_invoked_after_a_strategy_registration_is_resolved_using_Resolve_T()
        {
            Type   typeArg     = null;
            object instanceArg = null;

            var container = new PocketContainer()
                            .AddStrategy(type =>
            {
                if (type == typeof(string))
                {
                    return(c => "hello");
                }

                return(null);
            });

            container.AfterResolve += (type, instance) =>
            {
                typeArg     = type;
                instanceArg = instance;
                return(instance);
            };

            container.Resolve <string>();

            typeArg.Should().Be(typeof(string));
            instanceArg.Should().Be("hello");
        }
コード例 #22
0
        public void Registering_is_invoked_when_lazy_registration_occurs()
        {
            var receivedDelegates = new List <Delegate>();

            var container = new PocketContainer();

            container.Registering += (type, f) =>
            {
                receivedDelegates.Add(f);
                return(f);
            };

            container.AddStrategy(type =>
            {
                if (type == typeof(string))
                {
                    return(c => "hello");
                }

                return(null);
            });

            container.Resolve <string>();

            receivedDelegates
            .Should()
            .HaveCount(1);
            receivedDelegates
            .Single()
            .Should()
            .BeOfType <Func <PocketContainer, object> >();
        }
コード例 #23
0
        public void When_used_before_RegisterSingle_then_transform_is_only_called_once_per_instantiation()
        {
            var container = new PocketContainer()
                            .AfterCreating <HasDefaultCtor <int> >(obj =>
            {
                obj.Value++;
            })
                            .RegisterSingle(c => new HasDefaultCtor <int>());

            container.Resolve <HasDefaultCtor <int> >();
            container.Resolve <HasDefaultCtor <int> >();

            var resolved = container.Resolve <HasDefaultCtor <int> >();

            resolved.Value.Should().Be(1);
        }
コード例 #24
0
        internal static Func <PocketContainer, object> InMemoryEventSourcedRepositoryStrategy(Type type, PocketContainer container)
        {
            if (type.IsGenericType &&
                (type.GetGenericTypeDefinition() == typeof(IEventSourcedRepository <>) ||
                 type.GetGenericTypeDefinition() == typeof(InMemoryEventSourcedRepository <>)))
            {
                var aggregateType  = type.GenericTypeArguments.Single();
                var repositoryType = typeof(InMemoryEventSourcedRepository <>).MakeGenericType(aggregateType);

                var streamName = AggregateType.EventStreamName(aggregateType);

                // get the single registered event stream instance
                var stream = container.Resolve <ConcurrentDictionary <string, IEventStream> >()
                             .GetOrAdd(streamName,
                                       name => container.Clone()
                                       .Register(_ => name)
                                       .Resolve <IEventStream>());

                return(c => Activator.CreateInstance(repositoryType, stream, c.Resolve <IEventBus>()));
            }

            if (type == typeof(IEventStream))
            {
                return(c => c.Resolve <InMemoryEventStream>());
            }

            return(null);
        }
コード例 #25
0
        public void Optional_string_parameters_with_no_default_value_are_filled_correctly()
        {
            var container = new PocketContainer();

            var o = container.Resolve <TakesOptionalParamWithDefaultValueSpecifiedAsDefault <string> >();

            o.OptionalValue.Should().BeNull();
        }
コード例 #26
0
        public void Optional_parameters_for_non_primitive_types_are_passed_null_when_not_registered()
        {
            var container = new PocketContainer();

            var o = container.Resolve <TakesOptionalParamWithDefaultValueSpecifiedAsDefault <IAmAnInterface> >();

            o.OptionalValue.Should().BeNull();
        }
コード例 #27
0
        public void Open_generic_registrations_can_be_singletons()
        {
            var container = new PocketContainer();

            container
            .RegisterGeneric(
                variantsOf: typeof(IAmAGenericInterface <>),
                to: typeof(IAmAGenericImplementation <>),
                singletons: true);

            var resolvedOnce  = container.Resolve <IAmAGenericInterface <int> >();
            var resolvedTwice = container.Resolve <IAmAGenericInterface <int> >();

            resolvedOnce
            .Should()
            .BeSameAs(resolvedTwice);
        }
コード例 #28
0
        public void PocketContainer_is_implicitly_registered_to_itself()
        {
            var container = new PocketContainer();

            var resolvedContainer = container.Resolve <PocketContainer>();

            container.Should().BeSameAs(resolvedContainer);
        }
コード例 #29
0
        public void Optional_string_parameters_with_default_value_are_filled_correctly()
        {
            var container = new PocketContainer();

            var o = container.Resolve <TakesOptionalStringParamWithDefaultValue>();

            o.OptionalValue.Should().Be(TakesOptionalStringParamWithDefaultValue.DefaultValue);
        }
コード例 #30
0
        public void When_no_registration_exists_then_TryRegister_T_registers()
        {
            var container = new PocketContainer();

            container.TryRegister(c => "one");

            container.Resolve <string>().Should().Be("one");
        }
        public void When_multiple_implementations_are_found_then_an_error_is_thrown_on_Resolve()
        {
            var container = new PocketContainer()
                .IfOnlyOneImplementationUseIt();

            Action resolve = () => container.Resolve<IEnumerable>();
            resolve.ShouldThrow<ArgumentException>();
        }
コード例 #32
0
        public void Can_resolve_Func_of_unregistered_concrete_type_when_it_has_only_a_default_ctor()
        {
            var container = new PocketContainer();

            var result = container.Resolve <Func <HasDefaultCtor> >();

            result().Should().NotBeNull();
        }
        public void When_a_single_concrete_type_implementing_an_interface_is_found_then_it_is_Resolved()
        {
            var container = new PocketContainer()
                .IfOnlyOneImplementationUseIt();

            container.Resolve<IHaveOnlyOneImplementation>()
                     .Should()
                     .NotBeNull();
        }
        public void When_a_concrete_type_is_requested_then_it_is_Resolved()
        {
            var container = new PocketContainer()
                .IfOnlyOneImplementationUseIt();

            container.Resolve<Implements_IHaveOnlyOneImplementation>()
                     .Should()
                     .NotBeNull();
        }
        public void Types_with_names_ending_in_Settings_are_resolved_from_Settings_Get()
        {
            var container = new PocketContainer()
                .UseItsConfigurationForSettings();

            var settings = container.Resolve<PocketContainerStrategyTestSettings>();

            settings.Value.Should().Be("hello");
        }
        public void When_an_unregistered_interface_is_requested_then_a_mock_is_returned()
        {
            var container = new PocketContainer()
                .AutoMockInterfacesAndAbstractClasses();

            var strings = container.Resolve<IEnumerable<string>>();

            strings.Should().NotBeNull();
        }
        public void When_an_unregistered_abstract_class_is_requested_then_a_mock_is_returned()
        {
            var container = new PocketContainer()
                .AutoMockInterfacesAndAbstractClasses();

            var obj = container.Resolve<PocketContainerSingleImplementationStrategyTests.AbstractlyImplements_IHaveOnlyOneImplementation>();

            obj.Should().NotBeNull();
        }
コード例 #38
0
        public void A_strategy_on_the_clone_is_not_added_to_the_original()
        {
            var original = new PocketContainer();
            original.Clone().AutoMockInterfacesAndAbstractClasses();

            Action resolveFromOriginal = () =>
                original.Resolve<IEnumerable<string>>();

            resolveFromOriginal.ShouldThrow<ArgumentException>();
        }
        public void Empty_constructor_is_chosen_over_one_containing_a_DateTimeOffset()
        {
            var container = new PocketContainer().AvoidConstructorsWithPrimitiveTypes();

            var obj = container
                .Resolve<HasDefaultAndOneParamCtor<DateTimeOffset>>();

            obj.Should().NotBeNull();
            obj.Value.Should().Be(new DateTimeOffset());
        }
        public void An_open_generic_interface_can_be_registered_to_an_open_generic_type_and_resolved_correctly()
        {
            var container = new PocketContainer();

            container
                .Register<List<string>>(c => new List<string>())
                .RegisterGeneric(variantsOf: typeof (IEnumerable<>), to: typeof (List<>));

            container.Resolve<IEnumerable<string>>().Should().BeOfType<List<string>>();
        }
        public void A_constructor_with_a_primitive_is_chosen_if_no_other_is_available()
        {
            var container = new PocketContainer()
                .AvoidConstructorsWithPrimitiveTypes()
                .Register(c => "howdy");

            var obj = container
                .Resolve<HasTwoParamCtor<string, HasDefaultCtor>>();

            obj.Should().NotBeNull();
            obj.Value1.Should().Be("howdy");
        }
        public void Second_level_dependencies_are_resolved_from_the_dependency_resolver()
        {
            var innerContainer = new PocketContainer()
                .Register(c => "bonjour!");
            var resolver = new FakeDependencyResolver(innerContainer.Resolve);
            var container = new PocketContainer().IncludeDependencyResolver(resolver);

            var obj = container.Resolve<HasOneParamCtor<string>>();

            obj.Should().NotBeNull();
            obj.Value1.Should().Be("bonjour!");
        }
コード例 #43
0
        public void AfterResolve_can_be_used_to_modify_the_output_of_a_default_registration()
        {
            var container = new PocketContainer()
                .AfterResolve<HasDefaultCtor<int>>((c, obj) =>
                {
                    obj.Value ++;
                    return obj;
                });

            var resolved = container.Resolve<HasDefaultCtor<int>>();

            resolved.Value.Should().Be(1);
        }
コード例 #44
0
        public void AfterResolve_can_be_called_before_Register_but_still_applies()
        {
            var container = new PocketContainer()
                .AfterResolve<HashSet<string>>((c, hashSet) =>
                {
                    hashSet.Add("next");
                    return hashSet;
                })
                .Register(c =>
                {
                    var hashSet = new HashSet<string> { "initial" };
                    return hashSet;
                });

            var set = container.Resolve<HashSet<string>>();

            set.Should().Contain("initial");
            set.Should().Contain("next");
        }
コード例 #45
0
        public void AfterResolve_can_be_used_to_get_an_existing_registration_and_modify_its_output_before_returning_it()
        {
            var container = new PocketContainer()
                .Register(c =>
                {
                    var hashSet = new HashSet<string> { "initial" };
                    return hashSet;
                })
                .AfterResolve<HashSet<string>>((c, hashSet) =>
                {
                    hashSet.Add("next");
                    return hashSet;
                });

            var set = container.Resolve<HashSet<string>>();

            set.Should().Contain("initial");
            set.Should().Contain("next");
        }
コード例 #46
0
        public void Multiple_AfterResolve_functions_can_be_applied()
        {
            var container = new PocketContainer()
                .Register(c =>
                {
                    var hashSet = new HashSet<string> { "initial" };
                    return hashSet;
                })
                .AfterResolve<HashSet<string>>((c, hashSet) =>
                {
                    hashSet.Add("one");
                    return hashSet;
                })
                .AfterResolve<HashSet<string>>((c, hashSet) =>
                {
                    hashSet.Add("two");
                    return hashSet;
                });

            var set = container.Resolve<HashSet<string>>();

            set.Should().BeEquivalentTo(new object[] { "initial", "one", "two" });
        }
        public void Strategies_added_to_the_override_do_not_modify_the_primary()
        {
            var primary = new PocketContainer();
            var @override = primary.CreateOverrideContainer()
                                   .AutoMockInterfacesAndAbstractClasses();

            Action resolve = () => primary.Resolve<IEnumerable<string>>();

            resolve.ShouldThrow<ArgumentException>();
        }
        public void Non_empty_constructor_is_chosen_if_it_is_not_primitive()
        {
            var container = new PocketContainer()
                .AvoidConstructorsWithPrimitiveTypes();

            var obj = container
                .Resolve<HasDefaultAndOneParamCtor<HasDefaultCtor>>();

            obj.Should().NotBeNull();
            obj.Value.Should().NotBeNull();
        }
コード例 #49
0
        public void When_used_with_Register_then_AfterResolve_is_only_called_once_per_resolve()
        {
            var container = new PocketContainer()
                .Register(c => new HasDefaultCtor<int>())
                .AfterResolve<HasDefaultCtor<int>>((c, obj) =>
                {
                    obj.Value ++;
                    return obj;
                });

            container.Resolve<HasDefaultCtor<int>>();
            container.Resolve<HasDefaultCtor<int>>();
            container.Resolve<HasDefaultCtor<int>>();

            var resolved = container.Resolve<HasDefaultCtor<int>>();

            resolved.Value.Should().Be(3);
        }