Esempio n. 1
0
 /// <summary>
 ///     Configures dependency resolution to use PocketContainer.
 /// </summary>
 /// <param name="configuration">The configuration being configured.</param>
 /// <param name="container">The container to use to resolve dependencies.</param>
 /// <returns>
 ///     The same <see cref="HttpConfiguration" /> instance.
 /// </returns>
 public static HttpConfiguration ResolveDependenciesUsing(
     this HttpConfiguration configuration,
     PocketContainer container)
 {
     configuration.DependencyResolver = new PocketContainerDependencyResolver(container);
     return(configuration);
 }
        /// <summary>
        /// Registers an open generic type to another open generic type, allowing, for example, IService&amp;T&amp; to be registered to resolve to Service&amp;T&amp;.
        /// </summary>
        /// <param name="container">The container.</param>
        /// <param name="variantsOf">The open generic interface that callers will attempt to resolve, e.g. typeof(IService&amp;T&amp;).</param>
        /// <param name="to">The open generic type to resolve, e.g. typeof(Service&amp;T&amp;).</param>
        /// <param name="singletons">If true, each type will be lazily registered as a singleton.</param>
        /// <returns></returns>
        /// <exception cref="System.ArgumentException">
        /// Parameter 'variantsOf' is not an open generic type, e.g. typeof(IService&amp;T&amp;)
        /// or
        /// Parameter 'to' is not an open generic type, e.g. typeof(Service&amp;T&amp;)
        /// </exception>
        public static PocketContainer RegisterGeneric(this PocketContainer container, Type variantsOf, Type to, bool singletons = false)
        {
            if (!variantsOf.GetTypeInfo().IsGenericTypeDefinition)
            {
                throw new ArgumentException("Parameter 'variantsOf' is not an open generic type, e.g. typeof(IService<>)");
            }

            if (!to.GetTypeInfo().IsGenericTypeDefinition)
            {
                throw new ArgumentException("Parameter 'to' is not an open generic type, e.g. typeof(Service<>)");
            }

            return(container.AddStrategy(t =>
            {
                if (t.GetTypeInfo().IsGenericType&& t.GetGenericTypeDefinition() == variantsOf)
                {
                    var closedGenericType = to.MakeGenericType(t.GetTypeInfo().GenericTypeArguments);

                    if (singletons)
                    {
                        container.TryRegisterSingle(
                            t,
                            cc => cc.Resolve(closedGenericType));
                    }

                    return c => c.Resolve(closedGenericType);
                }
                return null;
            }));
        }
        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>();
        }
 /// <summary>
 ///     Configures dependency resolution to use PocketContainer.
 /// </summary>
 /// <param name="configuration">The configuration being configured.</param>
 /// <param name="container">The container to use to resolve dependencies.</param>
 /// <returns>
 ///     The same <see cref="HttpConfiguration" /> instance.
 /// </returns>
 public static HttpConfiguration ResolveDependenciesUsing(
     this HttpConfiguration configuration,
     PocketContainer container)
 {
     configuration.DependencyResolver = new PocketContainerDependencyResolver(container);
     return configuration;
 }
        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;
        }
        private static void AddFactoryToList <T>(
            PocketContainer container,
            Func <PocketContainer, T> factory)
        {
            // avoid re-entrancy which would result in a stack overflow
            if (recursionCounter.Value != 0)
            {
                return;
            }

            try
            {
                recursionCounter.Value++;

                // register IEnumerable<Func<PocketContainer, T>>
                container.TryRegister(c => c.Resolve <List <Func <PocketContainer, T> > >()
                                      .Select(f => f(c)));

                // register the registration list as a singleton
                container.TryRegisterSingle(c => new List <Func <PocketContainer, T> >());

                // resolve it and add the factory
                var registrations = container.Resolve <List <Func <PocketContainer, T> > >();

                registrations.Add(factory);
            }
            finally
            {
                recursionCounter.Value--;
            }
        }
Esempio n. 7
0
 public PocketContainerDependencyResolver(PocketContainer container)
 {
     if (container == null)
     {
         throw new ArgumentNullException("container");
     }
     this.container = container;
 }
 public PocketContainerDependencyResolver(PocketContainer container)
 {
     if (container == null)
     {
         throw new ArgumentNullException("container");
     }
     this.container = container;
 }
        private static void Register(
            this PocketContainer container,
            ServiceDescriptor descriptor)
        {
            if (descriptor.ImplementationInstance != null)
            {
                container.RegisterSingle(
                    descriptor.ServiceType,
                    c => descriptor.ImplementationInstance);
                return;
            }

            if (descriptor.ImplementationFactory != null)
            {
                if (descriptor.Lifetime != ServiceLifetime.Singleton)
                {
                    container.Register(
                        descriptor.ServiceType,
                        c => descriptor.ImplementationFactory(c));
                }
                else
                {
                    container.RegisterSingle(
                        descriptor.ServiceType,
                        c => descriptor.ImplementationFactory(c));
                }
                return;
            }

            if (descriptor.ImplementationType != null)
            {
                if (descriptor.IsOpenGeneric())
                {
                    container.RegisterGeneric(
                        variantsOf: descriptor.ServiceType,
                        to: descriptor.ImplementationType);
                }
                else if (descriptor.ServiceType == descriptor.ImplementationType)
                {
                    // no need to register it
                }
                else
                {
                    if (descriptor.Lifetime != ServiceLifetime.Singleton)
                    {
                        container.Register(
                            descriptor.ServiceType,
                            c => c.Resolve(descriptor.ImplementationType));
                    }
                    else
                    {
                        container.RegisterSingle(
                            descriptor.ServiceType,
                            c => c.Resolve(descriptor.ImplementationType));
                    }
                }
            }
        }
Esempio n. 10
0
 /// <summary>
 /// Clones the container, allowing for selectively overriding registrations without affecting the state of the original container.
 /// </summary>
 public PocketContainer Clone()
 {
     var clone = new PocketContainer
     {
         resolvers = new ConcurrentDictionary<Type, Func<PocketContainer, object>>(resolvers),
         strategyChain = strategyChain
     };
     return clone;
 }
Esempio n. 11
0
 public void ConfigureApplication(IAppBuilder app)
 {
     var config = new HttpConfiguration();
     var pocket = new PocketContainer();
     config.ResolveDependenciesUsing(pocket);
     pocket.Register(c => thisServersNode);
     config.MapHttpAttributeRoutes();
     app.UseWebApi(config);
 }
Esempio n. 12
0
        /// <summary>
        /// Clones the container, allowing for selectively overriding registrations without affecting the state of the original container.
        /// </summary>
        public PocketContainer Clone()
        {
            var clone = new PocketContainer
            {
                resolvers     = new ConcurrentDictionary <Type, Func <PocketContainer, object> >(resolvers),
                strategyChain = strategyChain
            };

            return(clone);
        }
        public static PocketContainer AccumulateRegistrations(
            this PocketContainer container)
        {
            container.Registering += (type, resolver) =>
            {
                AddFactoryToList(container, (dynamic)resolver);
                return(resolver);
            };

            return(container);
        }
Esempio n. 14
0
 public AfterResolvePipeline(
     PocketContainer container,
     Func <PocketContainer, object> originalResolver)
 {
     if (container == null)
     {
         throw new ArgumentNullException("container");
     }
     this.container       = container;
     originalRegistration = originalResolver;
 }
Esempio n. 15
0
            public AfterResolvePipeline(
                PocketContainer container,
                Func <PocketContainer, object> originalResolver)
            {
                this.container = container ?? throw new ArgumentNullException(nameof(container));

                if (originalResolver != null)
                {
                    InnerResolver = Resolve;

                    T Resolve(PocketContainer c) => (T)originalResolver(c);
                }
            }
Esempio n. 16
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            var container = new PocketContainer();

            GlobalConfiguration.Configuration
                               .ResolveDependenciesUsing(container);

            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            MvcRouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
 public static PocketContainer IncludeDependencyResolver(
     this PocketContainer container,
     IDependencyResolver dependencyResolver)
 {
     return(container.AddStrategy(type =>
     {
         if (dependencyResolver.GetService(type) != null)
         {
             return c => dependencyResolver.GetService(type);
         }
         return null;
     }));
 }
            public ServiceScope(PocketContainer container)
            {
                originalContainer = container ??
                                    throw new ArgumentNullException(nameof(container));
                clonedContainer = container.Clone();

                clonedContainer.AfterResolve += RegisterTransientsForDisposal;

                disposables = new CompositeDisposable
                {
                    () => clonedContainer.AfterResolve -= RegisterTransientsForDisposal,
                    () => isDisposed = true
                };
            }
        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);
                return c => Activator.CreateInstance(repositoryType,
                                                     c.Resolve<InMemoryEventStream>(),
                                                     c.Resolve<IEventBus>());
            }

            return null;
        }
Esempio n. 20
0
        public void ConfigureApplication(IAppBuilder app, string nodeId, IObservable<IEnumerable<Peer>> peerObserver)
        {
            thisServersNode = new Node(new NodeSettings(nodeId,
                                                      TimeSpan.FromSeconds(5),
                                                      TimeSpan.FromSeconds(1),
                                                      peerObserver));

            var config = new HttpConfiguration();
            var pocket = new PocketContainer();
            config.ResolveDependenciesUsing(pocket);
            pocket.RegisterSingle(c => thisServersNode);
            config.MapHttpAttributeRoutes();
            JsonSerialization(config);
            app.UseWebApi(config);
            thisServersNode.Start();
        }
        public static IServiceProvider AsServiceProvider(
            this PocketContainer container,
            IServiceCollection services)
        {
            foreach (var service in services)
            {
                Register(container, service);
            }

            container.RegisterSingle <IServiceProvider>(c => container)
            .RegisterSingle <IServiceScopeFactory>(c => new ServiceScopeFactory(c));

            container.AfterResolve += container.RegisterSingletonForDisposal;

            container.OnFailedResolve = (type, exception) => null;

            return(container);
        }
        public CommandSchedulerResolver(PocketContainer container)
        {
            if (container == null)
            {
                throw new ArgumentNullException(nameof(container));
            }

            schedulerResolversByAggregateTypeName = new Dictionary<string, Func<dynamic>>();

            Command.KnownTargetTypes.ForEach(aggregateType =>
            {
                var schedulerType = typeof (ICommandScheduler<>).MakeGenericType(aggregateType);

                schedulerResolversByAggregateTypeName.Add(
                    AggregateType.EventStreamName(aggregateType),
                    () => container.Resolve(schedulerType));
            });
        }
        public void Configuration_can_specify_a_dependency_resolver_which_is_then_used_when_resolving_handlers()
        {
            var container = new PocketContainer();
            container.Register(c => "hello");

            var configuration = new Configuration()
                .UseInMemoryEventStore()
                .UseDependency(resolve: resolve => (IEventBus) resolve(typeof (EventBusWithDependencies)))
                .UseDependency<IEnumerable<string>>(_ => new[] { "hello" });

            var bus = configuration.EventBus;

            bus.Should().BeOfType<EventBusWithDependencies>();

            var busWithDependencies = bus as EventBusWithDependencies;

            busWithDependencies.StringValues.Single().Should().Be("hello");
        }
 public static PocketContainer AutoMockInterfacesAndAbstractClasses(
     this PocketContainer container)
 {
     return(container.AddStrategy(type =>
     {
         if (type.IsInterface || type.IsAbstract)
         {
             var moqType = typeof(Mock <>).MakeGenericType(type);
             return c =>
             {
                 var mock = Activator.CreateInstance(moqType) as Mock;
                 mock.DefaultValue = DefaultValue.Mock;
                 return ((dynamic)mock).Object;
             };
         }
         return null;
     }));
 }
Esempio n. 25
0
        public static PocketContainer IfOnlyOneImplementationUseIt(
            this PocketContainer container)
        {
            return(container.AddStrategy(type =>
            {
                if (type.IsInterface || type.IsAbstract)
                {
                    var implementations = Discover.ConcreteTypes()
                                          .DerivedFrom(type)
                                          .ToArray();

                    if (implementations.Count() == 1)
                    {
                        return c => c.Resolve(implementations.Single());
                    }
                }
                return null;
            }));
        }
        /// <summary>
        /// Clones the container, allowing for selectively overriding registrations.
        /// </summary>
        public PocketContainer CreateOverrideContainer()
        {
            var fallback = this;

            var child = new PocketContainer
            {
                resolvers = new ConcurrentDictionary<Type, Func<PocketContainer, object>>(resolvers),
                strategyChain = strategyChain
            };

            return child.AddStrategy(t =>
            {
                // if the parent already has a registation, use it
                Func<PocketContainer, object> resolver;

                if (fallback.resolvers.TryGetValue(t, out resolver))
                {
                    return resolver;
                }

                return null;
            });
        }
        /// <summary>
        /// Clones the container, allowing for selectively overriding registrations.
        /// </summary>
        public PocketContainer CreateOverrideContainer()
        {
            var fallback = this;

            var child = new PocketContainer
            {
                resolvers     = new ConcurrentDictionary <Type, Func <PocketContainer, object> >(resolvers),
                strategyChain = strategyChain
            };

            return(child.AddStrategy(t =>
            {
                // if the parent already has a registation, use it
                Func <PocketContainer, object> resolver;

                if (fallback.resolvers.TryGetValue(t, out resolver))
                {
                    return resolver;
                }

                return null;
            }));
        }
        /// <summary>
        /// Registers an open generic type to another open generic type, allowing, for example, IService&amp;T&amp; to be registered to resolve to Service&amp;T&amp;.
        /// </summary>
        /// <param name="container">The container.</param>
        /// <param name="variantsOf">The open generic interface that callers will attempt to resolve, e.g. typeof(IService&amp;T&amp;).</param>
        /// <param name="to">The open generic type to resolve, e.g. typeof(Service&amp;T&amp;).</param>
        /// <returns></returns>
        /// <exception cref="System.ArgumentException">
        /// Parameter 'variantsOf' is not an open generic type, e.g. typeof(IService&amp;T&amp;)
        /// or
        /// Parameter 'to' is not an open generic type, e.g. typeof(Service&amp;T&amp;)
        /// </exception>
        public static PocketContainer RegisterGeneric(this PocketContainer container, Type variantsOf, Type to)
        {
            if (!variantsOf.IsGenericTypeDefinition)
            {
                throw new ArgumentException("Parameter 'variantsOf' is not an open generic type, e.g. typeof(IService<>)");
            }

            if (!to.IsGenericTypeDefinition)
            {
                throw new ArgumentException("Parameter 'to' is not an open generic type, e.g. typeof(Service<>)");
            }

            return(container.AddStrategy(t =>
            {
                if (t.IsGenericType && t.GetGenericTypeDefinition() == variantsOf)
                {
                    var closedGenericType = to.MakeGenericType(t.GetGenericArguments());

                    return c => c.Resolve(closedGenericType);
                }
                return null;
            }));
        }
 /// <summary>
 /// Configures a <see cref="PocketContainer" /> to prefer constructors that do not contain primitive types.
 /// </summary>
 /// <remarks>Primitive types include any type for which <see cref="Type.IsPrimitive" /> is true, as well as <see cref="String" />, <see cref="DateTime" />, and <see cref="DateTimeOffset" />.</remarks>
 /// <param name="container">The same container instance.</param>
 public static PocketContainer AvoidConstructorsWithPrimitiveTypes(
     this PocketContainer container)
 {
     return(container.AddStrategy(UseLongestConstructorHavingNoPrimitiveTypes));
 }
        internal static ICommandSchedulerDispatcher[] InitializeSchedulersPerAggregateType(
            PocketContainer container,
            GetClockName getClockName,
            ISubject<ICommandSchedulerActivity> subject)
        {
            var binders = AggregateType.KnownTypes
                                       .Select(aggregateType =>
                                       {
                                           var initializerType =
                                               typeof (SchedulerInitializer<>).MakeGenericType(aggregateType);

                                           dynamic initializer = container.Resolve(initializerType);

                                           return (ICommandSchedulerDispatcher) initializer.InitializeScheduler(
                                               subject,
                                               container,
                                               getClockName);
                                       })
                                       .ToArray();
            return binders;
        }
 public ServiceScopeFactory(PocketContainer container)
 {
     this.container = container ??
                      throw new ArgumentNullException(nameof(container));
 }