예제 #1
0
        public static PocketContainer DefaultToJsonSnapshots(this PocketContainer container)
        {
            return(container.AddStrategy(type =>
            {
                if (type.IsInterface &&
                    type.IsGenericType)
                {
                    if (type.GetGenericTypeDefinition() == typeof(ICreateSnapshot <>))
                    {
                        var snapshotCreatorType = typeof(JsonSnapshotter <>)
                                                  .MakeGenericType(type.GetGenericArguments().Single());

                        return c => c.Resolve(snapshotCreatorType);
                    }

                    if (type.GetGenericTypeDefinition() == typeof(IApplySnapshot <>))
                    {
                        var snapshotCreatorType = typeof(JsonSnapshotter <>)
                                                  .MakeGenericType(type.GetGenericArguments().Single());

                        return c => c.Resolve(snapshotCreatorType);
                    }
                }

                return null;
            }));
        }
        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!");
        }
        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> >();
        }
예제 #4
0
        internal static PocketContainer RegisterDefaultClockName(this PocketContainer container) =>
        container.AddStrategy(t =>
        {
            if (t == typeof(GetClockName))
            {
                return(c => new GetClockName(e => CommandScheduler.Clock.DefaultClockName));
            }

            return(null);
        });
예제 #5
0
        internal static PocketContainer AddFallbackToDefaultClock(this PocketContainer container)
        {
            return(container.AddStrategy(t =>
            {
                if (t == typeof(GetClockName))
                {
                    return c => new GetClockName(e => CommandScheduler.SqlCommandScheduler.DefaultClockName);
                }

                return null;
            }));
        }
 /// <summary>
 /// Uses Its.Configuration to resolve unregistered types whose name ends with "Settings".
 /// </summary>
 /// <param name="container">The container.</param>
 /// <returns>The same container instance.</returns>
 public static PocketContainer UseItsConfigurationForSettings(
     this PocketContainer container)
 {
     return(container.AddStrategy(type =>
     {
         if (!type.IsInterface &&
             !type.IsAbstract &&
             !type.IsGenericTypeDefinition &&
             type.Name.EndsWith("Settings"))
         {
             return c => Settings.Get(type);
         }
         return null;
     }));
 }
예제 #7
0
        public static PocketContainer UseImmediateCommandScheduling(this PocketContainer container)
        {
            return(container.AddStrategy(type =>
            {
                if (type.IsInterface &&
                    type.IsGenericType &&
                    type.GetGenericTypeDefinition() == typeof(ICommandScheduler <>))
                {
                    var targetType = type.GetGenericArguments().First();
                    var schedulerType = typeof(CommandScheduler <>).MakeGenericType(targetType);

                    return c => c.Resolve(schedulerType);
                }

                return null;
            }));
        }
        public static PocketContainer IfOnlyOneImplementationUseIt(
            this PocketContainer container)
        {
            return(container.AddStrategy(type =>
            {
                if (type.IsInterface || type.IsAbstract)
                {
                    var implementations = Discover.ConcreteTypesDerivedFrom(type)
                                          .ToArray();

                    if (implementations.Count() == 1)
                    {
                        var implementation = implementations.Single();
                        return c => c.Resolve(implementation);
                    }
                }
                return null;
            }));
        }
        public void Explicitly_registered_instances_are_not_overwritten_by_overriding_the_default_construction_strategy()
        {
            var ints      = Observable.Return(123);
            var container = new PocketContainer()
                            .Register(c => ints);

            // when someone asks for an unregistered interface, generate a mock
            container.AddStrategy(type => c =>
            {
                if (type.IsInterface)
                {
                    dynamic mock = Activator.CreateInstance(typeof(Mock <>).MakeGenericType(type));
                    return(mock.Object);
                }
                return(null);
            });

            container.Resolve <IObservable <string> >().Should().NotBeNull();
            container.Resolve <IObservable <int> >().Should().BeSameAs(ints);
        }
        public void When_a_strategy_has_resolved_an_unregistered_type_then_TryRegister_T_will_not_overwrite_it()
        {
            var container = new PocketContainer();

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

                return(null);
            });

            // trigger the strategy
            container.Resolve <string>();

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

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

            container.AddStrategy(type =>
            {
                if (type == typeof(IList <string>))
                {
                    container.RegisterSingle <IList <string> >(c => new List <string>());

                    return(c => c.Resolve <IList <string> >());
                }

                return(null);
            });

            var list1 = container.Resolve <IList <string> >();
            var list2 = container.Resolve <IList <string> >();

            list1.Should().BeSameAs(list2);
        }
        public void Default_construction_strategy_can_be_overridden_example_2_auto_mocking()
        {
            var container = new PocketContainer();

            // when someone asks for an IEnumerable<T> give back a List<T> containing the registered value
            container.AddStrategy(type =>
            {
                if (type.IsInterface)
                {
                    return(c =>
                    {
                        dynamic mock = Activator.CreateInstance(typeof(Mock <>).MakeGenericType(type));
                        return mock.Object;
                    });
                }
                return(null);
            });

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

            obj.Should().NotBeNull();
        }
예제 #13
0
        public static PocketContainer AddStoreStrategy(this PocketContainer container)
        {
            return(container.AddStrategy(type =>
            {
                if (type.IsInterface &&
                    type.IsGenericType &&
                    type.GetGenericTypeDefinition() == typeof(IStore <>))
                {
                    var targetType = type.GetGenericArguments().First();

                    Type applierType;
                    if (typeof(IEventSourced).IsAssignableFrom(targetType))
                    {
                        applierType = typeof(IEventSourcedRepository <>).MakeGenericType(targetType);

                        return c => c.Resolve(applierType);
                    }
                }

                return null;
            }));
        }
예제 #14
0
        public void Resolve_doesnt_result_in_cumulative_registrations()
        {
            var container = new PocketContainer();

            container.AddStrategy(t =>
            {
                if (t == typeof(int))
                {
                    var counter = 0;
                    return(c => ++ counter);
                }
                return(null);
            });

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

            Console.WriteLine(new { one, two });

            Action resolveEnumerable = () => container.Resolve <IEnumerable <int> >();

            resolveEnumerable.ShouldThrow <ArgumentException>();
        }
        public void Explicitly_registered_instances_are_not_overwritten_by_overriding_the_default_construction_strategy()
        {
            var ints      = Enumerable.Range(1, 123);
            var container = new PocketContainer()
                            .Register(c => ints);

            // when someone asks for an unregistered IEnumerable, return a list
            container.AddStrategy(type => c =>
            {
                if (type.GetTypeInfo().IsInterface)
                {
                    return(Activator.CreateInstance(typeof(List <>)
                                                    .MakeGenericType(
                                                        type.GetTypeInfo()
                                                        .GenericTypeArguments
                                                        .Single())));
                }
                return(null);
            });

            container.Resolve <IEnumerable <string> >().Should().NotBeNull();
            container.Resolve <IEnumerable <int> >().Should().BeSameAs(ints);
        }
        public void When_an_added_strategy_returns_null_then_it_falls_back_to_the_default()
        {
            var container = new PocketContainer()
                            .Register(c => "still here");

            // when someone asks for an IEnumerable<T> give back a List<T> containing the registered value
            container.AddStrategy(type =>
            {
                if (type.GetTypeInfo().IsInterface)
                {
                    return(c =>
                    {
                        dynamic mock = Activator.CreateInstance(typeof(List <>).MakeGenericType(type));
                        return mock.Object;
                    });
                }
                return(null);
            });

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

            obj.Should().NotBeNull();
            obj.Value1.Should().Be("still here");
        }
예제 #17
0
        public TestTargetRegistry Add(
            string environment,
            string application,
            Uri baseAddress,
            Action <TestDependencyRegistry> testDependencies = null)
        {
            if (baseAddress == null)
            {
                throw new ArgumentNullException(nameof(baseAddress));
            }
            if (!baseAddress.IsAbsoluteUri)
            {
                throw new ArgumentException("Base address must be an absolute URI.");
            }
            if (string.IsNullOrWhiteSpace(environment))
            {
                throw new ArgumentException("Value cannot be null or whitespace.", nameof(environment));
            }
            if (string.IsNullOrWhiteSpace(application))
            {
                throw new ArgumentException("Value cannot be null or whitespace.", nameof(application));
            }

            var container = new PocketContainer()
                            .Register(c => new HttpClient())
                            .RegisterSingle(c => new TestTarget(c.Resolve)
            {
                Application = application,
                Environment = environment,
                BaseAddress = baseAddress
            });

            if (services != null)
            {
                // fall back to application's IServiceProvider
                container.AddStrategy(type =>
                {
                    if (typeof(IPeakyTest).IsAssignableFrom(type))
                    {
                        return(null);
                    }

                    return(c => services.GetRequiredService(type));
                });
            }

            testDependencies?.Invoke(new TestDependencyRegistry((t, func) => container.Register(t, c => func())));

            container.AfterCreating <HttpClient>(client =>
            {
                if (client.BaseAddress == null)
                {
                    client.BaseAddress = baseAddress;
                }
                return(client);
            });

            targets.Add($"{environment}:{application}",
                        new Lazy <TestTarget>(() => container.Resolve <TestTarget>()));

            return(this);
        }