Example #1
0
        public void CreateFromFactory_executes_factory_with_resolved_parameters([Frozen] IFulfilsResolutionRequests resolver,
                                                                                InstanceCreator sut,
                                                                                IFactoryAdapter factory,
                                                                                ResolutionPath path,
                                                                                IServiceRegistration registration,
                                                                                object resolved,
                                                                                [MockParam(typeof(string), Name = "Foo")] ParameterInfo paramOne,
                                                                                object paramOneValue,
                                                                                [MockParam(typeof(int), Name = "Bar")] ParameterInfo paramTwo,
                                                                                object paramTwoValue)
        {
            // Arrange
            Mock.Get(factory).SetupGet(x => x.RequiresParameterResolution).Returns(true);
            Mock.Get(factory).Setup(x => x.GetParameters()).Returns(new [] { paramOne, paramTwo });
            Mock.Get(resolver)
            .Setup(x => x.Resolve(It.Is <ResolutionRequest>(r => r.Name == paramOne.Name && r.ServiceType == paramOne.ParameterType)))
            .Returns(() => ResolutionResult.Success(path, paramOneValue));
            Mock.Get(resolver)
            .Setup(x => x.Resolve(It.Is <ResolutionRequest>(r => r.Name == paramTwo.Name && r.ServiceType == paramTwo.ParameterType)))
            .Returns(() => ResolutionResult.Success(path, paramTwoValue));
            Mock.Get(factory)
            .Setup(x => x.Execute(It.Is <object[]>(e => e.Length == 2 && e[0] == paramOneValue && e[1] == paramTwoValue)))
            .Returns(resolved);

            // Act
            var result = sut.CreateFromFactory(factory, path, registration);

            // Assert
            Mock.Get(factory)
            .Verify(x => x.Execute(It.Is <object[]>(e => e.Length == 2 && e[0] == paramOneValue && e[1] == paramTwoValue)), Times.Once);
            Assert.That(result, Is.SameAs(resolved));
        }
Example #2
0
        private IList <MemberBinding> GetMemberBindings(IContainerContext containerContext,
                                                        IServiceRegistration serviceRegistration,
                                                        ResolutionContext resolutionContext)
        {
            var length  = serviceRegistration.InjectionMembers.Length;
            var members = new List <MemberBinding>();

            for (var i = 0; i < length; i++)
            {
                var info = serviceRegistration.InjectionMembers[i];
                if (!info.CanInject(containerContext.ContainerConfigurator.ContainerConfiguration,
                                    serviceRegistration.RegistrationContext))
                {
                    continue;
                }

                var expression = containerContext.ResolutionStrategy
                                 .BuildResolutionExpression(containerContext, resolutionContext, info.TypeInformation, serviceRegistration.RegistrationContext.InjectionParameters);

                if (expression == null)
                {
                    continue;
                }

                members.Add(info.MemberInfo.AssignTo(expression));
            }

            return(members);
        }
Example #3
0
        protected override Expression GetExpressionInternal(IServiceRegistration serviceRegistration, ResolutionInfo resolutionInfo, Type resolveType)
        {
            if (this.expression != null)
            {
                return(this.expression);
            }
            lock (this.syncObject)
            {
                if (this.expression != null)
                {
                    return(this.expression);
                }

                var expr = this.expressionBuilder.CreateFillExpression(serviceRegistration, Expression.Constant(serviceRegistration.RegistrationContext.ExistingInstance),
                                                                       resolutionInfo, serviceRegistration.ImplementationType);
                var factory = expr.CompileDelegate(Constants.ScopeExpression);

                var instance = factory(resolutionInfo.ResolutionScope);

                if (serviceRegistration.ShouldHandleDisposal && instance is IDisposable disposable)
                {
                    resolutionInfo.RootScope.AddDisposableTracking(disposable);
                }

                if (serviceRegistration.RegistrationContext.Finalizer != null)
                {
                    var finalizerExpression = base.HandleFinalizer(Expression.Constant(instance), serviceRegistration);
                    return(this.expression = Expression.Constant(finalizerExpression.CompileDelegate(Constants.ScopeExpression)(resolutionInfo.ResolutionScope)));
                }

                return(this.expression = Expression.Constant(instance));
            }
        }
Example #4
0
        private void CreateMethodExpressions(IContainerContext containerContext, IServiceRegistration serviceRegistration, ResolutionContext resolutionContext, Expression newExpression, Expression[] buffer)
        {
            var length = serviceRegistration.MetaInformation.InjectionMethods.Length;

            for (var i = 0; i < length; i++)
            {
                var info = serviceRegistration.MetaInformation.InjectionMethods[i];

                var paramLength = info.Parameters.Length;
                if (paramLength == 0)
                {
                    buffer[i] = newExpression.CallMethod(info.Method);
                }
                else
                {
                    var parameters = new Expression[paramLength];
                    for (var j = 0; j < paramLength; j++)
                    {
                        parameters[j] = containerContext.ResolutionStrategy.BuildResolutionExpression(containerContext, resolutionContext,
                                                                                                      info.Parameters[j], serviceRegistration.RegistrationContext.InjectionParameters);
                    }

                    buffer[i] = newExpression.CallMethod(info.Method, parameters);
                }
            }
        }
Example #5
0
        public Expression CreateFillExpression(IContainerContext containerContext,
                                               IServiceRegistration serviceRegistration,
                                               Expression instance,
                                               ResolutionContext resolutionContext,
                                               Type serviceType)
        {
            var lines = new List <Expression>();

            if (instance.Type != serviceType)
            {
                instance = instance.ConvertTo(serviceType);
            }

            var variable = serviceType.AsVariable();
            var assign   = variable.AssignTo(instance);

            lines.Add(assign);

            if (serviceRegistration.InjectionMembers.Length > 0)
            {
                lines.AddRange(this.FillMembersExpression(containerContext, serviceRegistration.InjectionMembers,
                                                          serviceRegistration.RegistrationContext, resolutionContext, variable));
            }

            if (serviceRegistration.InjectionMethods.Length > 0 || serviceRegistration.RegistrationContext.Initializer != null || this.containerExtensionManager.HasPostBuildExtensions)
            {
                lines.AddRange(this.CreatePostWorkExpressionIfAny(containerContext, serviceRegistration, resolutionContext, serviceType, variable));
            }

            lines.Add(variable); //block returns with the variable

            return(lines.AsBlock(variable));
        }
Example #6
0
        private IEnumerable <MemberBinding> GetMemberBindings(IServiceRegistration serviceRegistration, ResolutionInfo resolutionInfo)
        {
            var length  = serviceRegistration.MetaInformation.InjectionMembers.Length;
            var members = new List <MemberBinding>();

            for (var i = 0; i < length; i++)
            {
                var info = serviceRegistration.MetaInformation.InjectionMembers[i];
                if (!this.CanInjectMember(info, serviceRegistration))
                {
                    continue;
                }

                var expression = this.containerContext.ResolutionStrategy
                                 .BuildResolutionExpression(this.containerContext, resolutionInfo, info.TypeInformation, serviceRegistration.RegistrationContext.InjectionParameters);

                if (expression == null)
                {
                    continue;
                }

                members.Add(Expression.Bind(info.MemberInfo, expression));
            }

            return(members);
        }
Example #7
0
        private async void MonitorServiceRegistration(CancellationToken _cancellationToken)
        {
            try
            {
                await Task.Delay(RegistrationCheckPeriodInSeconds * 1000, _cancellationToken);

                while (!_cancellationToken.IsCancellationRequested)
                {
                    if (_registration != null)
                    {
                        var serviceInstanceInfo = await _discovery.FindServiceByInstanceName(_registration.InstanceName);

                        if (serviceInstanceInfo == null)
                        {
                            _registration = await _discovery.RegisterService();
                        }
                    }
                    await Task.Delay(RegistrationCheckPeriodInSeconds * 1000, _cancellationToken);
                }
                _log.Info("Service registration monitor stopped.");
            }
            catch (OperationCanceledException)
            {
                _log.Info("Service registration monitor stopped.");
            }
        }
Example #8
0
        public Expression CreateFillExpression(IServiceRegistration serviceRegistration, Expression instance,
                                               ResolutionInfo resolutionInfo, Type serviceType)
        {
            var block = new List <Expression>();

            if (instance.Type != serviceType)
            {
                instance = Expression.Convert(instance, serviceType);
            }

            var variable = Expression.Variable(serviceType);
            var assign   = Expression.Assign(variable, instance);

            block.Add(assign);

            if (serviceRegistration.MetaInformation.InjectionMembers.Length > 0)
            {
                block.AddRange(this.FillMembersExpression(serviceRegistration, resolutionInfo, variable));
            }

            if (serviceRegistration.MetaInformation.InjectionMethods.Length > 0 || this.containerExtensionManager.HasPostBuildExtensions)
            {
                return(this.CreatePostWorkExpressionIfAny(serviceRegistration, resolutionInfo, variable, serviceType, block, variable));
            }

            block.Add(variable); //return

            return(Expression.Block(new[] { variable }, block));
        }
Example #9
0
        private Expression[] CreateMethodExpressions(IServiceRegistration serviceRegistration, ResolutionInfo resolutionInfo, Expression newExpression)
        {
            var length            = serviceRegistration.MetaInformation.InjectionMethods.Length;
            var methodExpressions = new Expression[length];

            for (var i = 0; i < length; i++)
            {
                var info = serviceRegistration.MetaInformation.InjectionMethods[i];

                var paramLength = info.Parameters.Length;
                if (paramLength == 0)
                {
                    methodExpressions[i] = Expression.Call(newExpression, info.Method, new Expression[0]);
                }
                else
                {
                    var parameters = new Expression[paramLength];
                    for (var j = 0; j < paramLength; j++)
                    {
                        parameters[j] = this.containerContext.ResolutionStrategy.BuildResolutionExpression(this.containerContext, resolutionInfo,
                                                                                                           info.Parameters[j], serviceRegistration.RegistrationContext.InjectionParameters);
                    }

                    methodExpressions[i] = Expression.Call(newExpression, info.Method, parameters);
                }
            }

            return(methodExpressions);
        }
Example #10
0
        private Expression CreatePostWorkExpressionIfAny(IServiceRegistration serviceRegistration, ResolutionInfo resolutionInfo,
                                                         Expression initExpression, Type serviceType, List <Expression> block = null, ParameterExpression variable = null)
        {
            block = block ?? new List <Expression>();

            var newVariable = variable ?? Expression.Variable(initExpression.Type);

            if (variable == null)
            {
                block.Add(Expression.Assign(newVariable, initExpression));
            }

            if (serviceRegistration.MetaInformation.InjectionMethods.Length > 0)
            {
                block.AddRange(this.CreateMethodExpressions(serviceRegistration, resolutionInfo, newVariable));
            }

            if (this.containerExtensionManager.HasPostBuildExtensions)
            {
                var call = Expression.Call(Expression.Constant(this.containerExtensionManager), Constants.BuildExtensionMethod, newVariable, Expression.Constant(this.containerContext),
                                           Expression.Constant(resolutionInfo), Expression.Constant(serviceRegistration), Expression.Constant(serviceType));

                block.Add(Expression.Assign(newVariable, Expression.Convert(call, initExpression.Type)));
            }

            block.Add(newVariable); //return

            return(Expression.Block(new[] { newVariable }, block));
        }
Example #11
0
        private bool TryBuildResolutionConstructor(
            ConstructorInformation constructor,
            ResolutionContext resolutionContext,
            IContainerContext containerContext,
            IServiceRegistration serviceRegistration,
            out TypeInformation failedParameter,
            out Expression[] parameterExpressions,
            bool skipUknownResolution = false)
        {
            var paramLength = constructor.Parameters.Length;

            parameterExpressions = new Expression[paramLength];
            failedParameter      = null;
            for (var i = 0; i < paramLength; i++)
            {
                var parameter = constructor.Parameters[i];

                parameterExpressions[i] = containerContext.ResolutionStrategy.BuildResolutionExpression(containerContext, resolutionContext,
                                                                                                        parameter, serviceRegistration.RegistrationContext.InjectionParameters, skipUknownResolution);

                if (parameterExpressions[i] == null)
                {
                    failedParameter = parameter;
                    return(false);
                }
            }

            return(true);
        }
Example #12
0
        /// <inheritdoc />
        public override Expression GetExpression(IContainerContext containerContext, IServiceRegistration serviceRegistration, IObjectBuilder objectBuilder, ResolutionContext resolutionContext, Type resolveType)
        {
            if (this.expression != null)
            {
                return(this.expression);
            }
            lock (this.syncObject)
            {
                if (this.expression != null)
                {
                    return(this.expression);
                }
                var expr = base.GetExpression(containerContext, serviceRegistration, objectBuilder, resolutionContext, resolveType);
                if (expr == null)
                {
                    return(null);
                }

                object instance;
                if (expr.NodeType == ExpressionType.New && ((NewExpression)expr).Arguments.Count == 0)
                {
                    instance = Activator.CreateInstance(expr.Type);
                }
                else
                {
                    instance = expr.CompileDelegate(resolutionContext)(resolutionContext.RootScope);
                }

                this.expression = instance.AsConstant();
            }

            return(this.expression);
        }
Example #13
0
        protected override Expression GetExpressionInternal(IServiceRegistration serviceRegistration, ResolutionInfo resolutionInfo, Type resolveType)
        {
            var genericType  = serviceRegistration.ImplementationType.MakeGenericType(resolveType.GetGenericArguments());
            var registration = this.RegisterConcreteGenericType(serviceRegistration, resolveType, genericType);

            return(registration.GetExpression(resolutionInfo, resolveType));
        }
Example #14
0
 private static void RegisterElasticsearchReadStore <TReadModel>(
     IServiceRegistration serviceRegistration)
     where TReadModel : class, IReadModel
 {
     serviceRegistration.Register <IElasticsearchReadModelStore <TReadModel>, ElasticsearchReadModelStore <TReadModel> >();
     serviceRegistration.Register <IReadModelStore <TReadModel> >(r => r.Resolver.Resolve <IElasticsearchReadModelStore <TReadModel> >());
 }
Example #15
0
        public IStashboxContainer ReMap(IServiceRegistration serviceRegistration, IRegistrationContext registrationContext)
        {
            if (serviceRegistration.IsDecorator)
            {
                this.containerContext.DecoratorRepository.AddDecorator(registrationContext.ServiceType, serviceRegistration,
                                                                       true, false);
            }
            else
            {
                if (registrationContext.AdditionalServiceTypes.Length > 0)
                {
                    foreach (var additionalServiceType in registrationContext.AdditionalServiceTypes)
                    {
                        this.containerContext.RegistrationRepository.AddOrUpdateRegistration(serviceRegistration, additionalServiceType, true, false);
                    }
                }

                this.containerContext.RegistrationRepository.AddOrUpdateRegistration(serviceRegistration, registrationContext.ServiceType, true, false);
            }

            this.containerContext.Container.RootScope.InvalidateDelegateCache();

            this.containerExtensionManager.ExecuteOnRegistrationExtensions(this.containerContext, serviceRegistration);

            return(this.containerContext.Container);
        }
Example #16
0
        protected Expression HandleFinalizer(Expression instanceExpression, IServiceRegistration serviceRegistration)
        {
            var addFinalizerMethod = Constants.AddWithFinalizerMethod.MakeGenericMethod(instanceExpression.Type);

            return(Expression.Call(Constants.ScopeExpression, addFinalizerMethod, instanceExpression,
                                   Expression.Constant(serviceRegistration.RegistrationContext.Finalizer)));
        }
Example #17
0
        /// <summary>
        /// Resolves the given resolution request, using the given service registration.
        /// </summary>
        /// <param name="request">Request.</param>
        /// <param name="registration">Registration.</param>
        protected virtual ResolutionResult Resolve(ResolutionRequest request, IServiceRegistration registration)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }
            AssertIsValidRequest(request);

            if (registration == null)
            {
                return(ResolutionResult.Failure(request.ResolutionPath));
            }

            var factory = registration.GetFactoryAdapter(request);

            if (factory == null)
            {
                return(ResolutionResult.Failure(request.ResolutionPath));
            }

            var resolved = instanceCreator.CreateFromFactory(factory, request.ResolutionPath, registration);

            InvokeServiceResolved(registration, resolved);
            return(ResolutionResult.Success(request.ResolutionPath, resolved));
        }
 public void Register(IServiceRegistration services, IDictionary <string, object> data)
 {
     services.RegisterSingleton(r => r
                                .Types(t => t.AssignableTo <IValidator>())
                                .As(s => s.Self().ImplementedInterfaces())
                                );
 }
Example #19
0
        //private readonly IViewRenderService _viewRenderService;
        //readonly IConfiguration _configuration;
        //private readonly IEmailSender _emailSender;

        public CartController(IServiceRegistration serviceRegistration)
        {
            _serviceRegistration = serviceRegistration;
            //_viewRenderService = viewRenderService;
            //_configuration = configuration;
            //_emailSender = emailSender;
        }
Example #20
0
        /// <summary>
        /// Lookups the service references.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <returns>IServiceReference[].</returns>
        /// Performs a lookup for ServiceReferences that are bound to this
        /// ServiceRegistry using the specified BundleContext.
        /// @param context The BundleContext to lookup the ServiceReferences on.
        /// @return An array of all matching ServiceReferences or null if none
        /// exist.
        public IServiceReference[] LookupServiceReferences(IBundleContext context)
        {
            int size;
            List <IServiceReference>    references;
            List <IServiceRegistration> serviceRegs = (List <IServiceRegistration>)PublishedServicesByContext[context];

            if (serviceRegs == null)
            {
                return(null);
            }

            size = serviceRegs.Count;

            if (size == 0)
            {
                return(null);
            }

            references = new List <IServiceReference>();
            for (int i = 0; i < size; i++)
            {
                IServiceRegistration registration = (IServiceRegistration)serviceRegs[i];

                IServiceReference reference = registration.GetReference();
                references.Add(reference);
            }

            if (references.Count == 0)
            {
                return(null);
            }

            return((IServiceReference[])references.ToArray());
        }
Example #21
0
        /// <summary>
        /// Unpublishes the services.
        /// </summary>
        /// <param name="context">The context.</param>
        /// Unpublishes all services from this ServiceRegistry that the
        /// specified BundleContext registered.
        /// @param context the BundleContext to unpublish all services for.
        public void UnpublishServices(IBundleContext context)
        {
            // Get all the Services published by the BundleContext.
            List <IServiceRegistration> serviceRegs = (List <IServiceRegistration>)PublishedServicesByContext[context];

            if (serviceRegs != null)
            {
                // Remove this list for the BundleContext
                PublishedServicesByContext.Remove(context);
                int size = serviceRegs.Count();
                for (int i = 0; i < size; i++)
                {
                    IServiceRegistration serviceReg = (IServiceRegistration)serviceRegs[i];
                    // Remove each service from the list of all published Services
                    AllPublishedServices.Remove(serviceReg);

                    // Remove each service from the list of Services published by Class Name.
                    string[] clazzes    = ((ServiceRegistration)serviceReg).Classes;
                    int      numclazzes = clazzes.Length;

                    for (int j = 0; j < numclazzes; j++)
                    {
                        string clazz = clazzes[j];
                        if (PublishedServicesByClass.ContainsKey(clazz))
                        {
                            List <IServiceRegistration> services = (List <IServiceRegistration>)PublishedServicesByClass[clazz];
                            services.Remove(serviceReg);
                        }
                    }
                }
            }
        }
        /// <summary>
        /// Scan and Register services using the specified <paramref name="builder"/> for the specified <paramref name="lifetime"/>.
        /// </summary>
        /// <param name="services">The <see cref="IServiceRegistration"/> to add the service to.</param>
        /// <param name="builder">The builder delegate used to scan and register services</param>
        /// <param name="lifetime">The service lifetime.</param>
        /// <returns>A reference to this instance after the operation has completed.</returns>
        public static IServiceRegistration Register(this IServiceRegistration services, Action <IServiceRegistrationBuilder> builder, ServiceLifetime lifetime)
        {
            if (services == null)
            {
                throw new ArgumentNullException(nameof(services));
            }
            if (builder == null)
            {
                throw new ArgumentNullException(nameof(builder));
            }

            var types = services.ServiceContext.Types;

            var serviceBuilder = new ServiceRegistrationBuilder(types);

            builder(serviceBuilder);

            var mapping = serviceBuilder.TypeMaps;

            foreach (var typeMap in mapping)
            {
                foreach (var serviceType in typeMap.ServiceTypes)
                {
                    services.Register(serviceType, typeMap.ImplementationType, lifetime);
                }
            }

            return(services);
        }
Example #23
0
        /// <summary>
        /// Disposes of a single component instance, matching a given registration.
        /// </summary>
        /// <param name="registration">Registration.</param>
        /// <param name="instanceCache">Instance cache.</param>
        protected virtual void Dispose(IServiceRegistration registration, ICachesResolvedServiceInstances instanceCache)
        {
            if (registration == null)
            {
                throw new ArgumentNullException(nameof(registration));
            }
            if (instanceCache == null)
            {
                throw new ArgumentNullException(nameof(instanceCache));
            }

            object instance;

            if (!instanceCache.TryGet(registration, out instance))
            {
                return;
            }

            if (!(instance is IDisposable))
            {
                return;
            }

            ((IDisposable)instance).Dispose();
        }
        IDictionary <ServiceRegistrationKey, IServiceRegistration> GetNonConflictingRegistrations(IEnumerable <ServiceRegistrationKey> alreadyFound,
                                                                                                  IServiceRegistrationProvider provider,
                                                                                                  Type serviceTypeFilter)
        {
            if (alreadyFound == null)
            {
                throw new ArgumentNullException(nameof(alreadyFound));
            }
            if (provider == null)
            {
                throw new ArgumentNullException(nameof(provider));
            }

            var candidates = (serviceTypeFilter != null)? provider.GetAll(serviceTypeFilter) : provider.GetAll();

            if (candidates == null)
            {
                candidates = new IServiceRegistration[0];
            }

            return((from registration in candidates
                    let key = ServiceRegistrationKey.ForRegistration(registration)
                              where !alreadyFound.Contains(key)
                              select new { Registration = registration, Key = key })
                   .ToDictionary(k => k.Key, v => v.Registration));
        }
Example #25
0
        private ResolutionConstructor SelectConstructor(IServiceRegistration serviceRegistration, ResolutionInfo resolutionInfo, ConstructorInformation[] constructors)
        {
            var length = constructors.Length;
            var checkedConstructors = new Dictionary <ConstructorInfo, TypeInformation>();

            for (var i = 0; i < length; i++)
            {
                var constructor          = constructors[i];
                var paramLength          = constructor.Parameters.Length;
                var parameterExpressions = new Expression[paramLength];

                var             hasNullParameter = false;
                TypeInformation failedParameter  = null;
                for (var j = 0; j < paramLength; j++)
                {
                    var parameter = constructor.Parameters[j];

                    var expression = this.containerContext.ResolutionStrategy.BuildResolutionExpression(this.containerContext,
                                                                                                        resolutionInfo, parameter, serviceRegistration.RegistrationContext.InjectionParameters);

                    if (expression == null)
                    {
                        hasNullParameter = true;
                        failedParameter  = parameter;
                        break;
                    }

                    parameterExpressions[j] = expression;
                }

                if (hasNullParameter)
                {
                    if (!resolutionInfo.NullResultAllowed)
                    {
                        checkedConstructors.Add(constructor.Constructor, failedParameter);
                    }

                    continue;
                }

                return(new ResolutionConstructor {
                    Constructor = constructor.Constructor, Parameters = parameterExpressions
                });
            }

            if (resolutionInfo.NullResultAllowed)
            {
                return(null);
            }

            var stringBuilder = new StringBuilder();

            foreach (var checkedConstructor in checkedConstructors)
            {
                stringBuilder.AppendLine($"Checked constructor {checkedConstructor.Key}, unresolvable parameter: ({checkedConstructor.Value.Type}){checkedConstructor.Value.ParameterName}");
            }

            throw new ResolutionFailedException(serviceRegistration.ImplementationType, stringBuilder.ToString());
        }
Example #26
0
        private void RegisterDefaults(IServiceRegistration serviceRegistration)
        {
            serviceRegistration.Register <ILog, ConsoleLog>();
            serviceRegistration.Register <IAggregateStoreResilienceStrategy, NoAggregateStoreResilienceStrategy>();
            serviceRegistration.Register <IDispatchToReadStoresResilienceStrategy, NoDispatchToReadStoresResilienceStrategy>();
            serviceRegistration.Register <ISagaUpdateResilienceStrategy, NoSagaUpdateResilienceStrategy>();
            serviceRegistration.Register <IDispatchToSubscriberResilienceStrategy, NoDispatchToSubscriberResilienceStrategy>();
            serviceRegistration.Register <IDispatchToReadStores, DispatchToReadStores>();
            serviceRegistration.Register <IEventStore, EventStoreBase>();
            serviceRegistration.Register <IEventPersistence, InMemoryEventPersistence>(Lifetime.Singleton);
            serviceRegistration.Register <ICommandBus, CommandBus>();
            serviceRegistration.Register <IAggregateStore, AggregateStore>();
            serviceRegistration.Register <ISnapshotStore, SnapshotStore>();
            serviceRegistration.Register <ISnapshotSerilizer, SnapshotSerilizer>();
            serviceRegistration.Register <ISnapshotPersistence, NullSnapshotPersistence>();
            serviceRegistration.Register <ISnapshotUpgradeService, SnapshotUpgradeService>();
            serviceRegistration.Register <ISnapshotDefinitionService, SnapshotDefinitionService>(Lifetime.Singleton);
            serviceRegistration.Register <IReadModelPopulator, ReadModelPopulator>();
            serviceRegistration.Register <IEventJsonSerializer, EventJsonSerializer>();
            serviceRegistration.Register <IEventDefinitionService, EventDefinitionService>(Lifetime.Singleton);
            serviceRegistration.Register <IQueryProcessor, QueryProcessor>();
            serviceRegistration.Register <IJsonSerializer, JsonSerializer>(Lifetime.Singleton);
            serviceRegistration.Register <IJsonOptions, JsonOptions>();
            serviceRegistration.Register <IJobScheduler, InstantJobScheduler>();
            serviceRegistration.Register <IJobRunner, JobRunner>();
            serviceRegistration.Register <IJobDefinitionService, JobDefinitionService>(Lifetime.Singleton);
            serviceRegistration.Register <IOptimisticConcurrencyRetryStrategy, OptimisticConcurrencyRetryStrategy>();
            serviceRegistration.Register <IEventUpgradeManager, EventUpgradeManager>(Lifetime.Singleton);
            serviceRegistration.Register <IAggregateFactory, AggregateFactory>();
            serviceRegistration.Register <IReadModelDomainEventApplier, ReadModelDomainEventApplier>();
            serviceRegistration.Register <IDomainEventPublisher, DomainEventPublisher>();
            serviceRegistration.Register <ISerializedCommandPublisher, SerializedCommandPublisher>();
            serviceRegistration.Register <ICommandDefinitionService, CommandDefinitionService>(Lifetime.Singleton);
            serviceRegistration.Register <IDispatchToEventSubscribers, DispatchToEventSubscribers>();
            serviceRegistration.Register <IDomainEventFactory, DomainEventFactory>(Lifetime.Singleton);
            serviceRegistration.Register <ISagaDefinitionService, SagaDefinitionService>(Lifetime.Singleton);
            serviceRegistration.Register <ISagaStore, SagaAggregateStore>();
            serviceRegistration.Register <ISagaErrorHandler, SagaErrorHandler>();
            serviceRegistration.Register <IDispatchToSagas, DispatchToSagas>();
#if NET452
            serviceRegistration.Register <IMemoryCache, MemoryCache>(Lifetime.Singleton);
#else
            serviceRegistration.Register <IMemoryCache, DictionaryMemoryCache>(Lifetime.Singleton);
#endif
            serviceRegistration.RegisterGeneric(typeof(ISagaUpdater <, , ,>), typeof(SagaUpdater <, , ,>));
            serviceRegistration.Register <IEventFlowConfiguration>(_ => _eventFlowConfiguration);
            serviceRegistration.Register <ICancellationConfiguration>(_ => _eventFlowConfiguration);
            serviceRegistration.RegisterGeneric(typeof(ITransientFaultHandler <>), typeof(TransientFaultHandler <>));
            serviceRegistration.RegisterGeneric(typeof(IReadModelFactory <>), typeof(ReadModelFactory <>), Lifetime.Singleton);
            serviceRegistration.Register <IBootstrap, DefinitionServicesInitilizer>();
            serviceRegistration.Register(_ => ModuleRegistration, Lifetime.Singleton);
            serviceRegistration.Register <ILoadedVersionedTypes>(r => new LoadedVersionedTypes(
                                                                     _jobTypes,
                                                                     _commandTypes,
                                                                     _aggregateEventTypes,
                                                                     _sagaTypes,
                                                                     _snapshotTypes),
                                                                 Lifetime.Singleton);
        }
Example #27
0
 private static void RegisterInMemoryReadStore <TReadModel>(
     IServiceRegistration serviceRegistration)
     where TReadModel : class, IReadModel
 {
     serviceRegistration.Register <IInMemoryReadStore <TReadModel>, InMemoryReadStore <TReadModel> >(Lifetime.Singleton);
     serviceRegistration.Register <IReadModelStore <TReadModel> >(r => r.Resolver.Resolve <IInMemoryReadStore <TReadModel> >());
     serviceRegistration.Register <IQueryHandler <InMemoryQuery <TReadModel>, IReadOnlyCollection <TReadModel> >, InMemoryQueryHandler <TReadModel> >();
 }
 private static void RegisterMssqlReadStore <TReadModel>(
     IServiceRegistration serviceRegistration)
     where TReadModel : class, IReadModel
 {
     serviceRegistration.Register <IReadModelSqlGenerator, ReadModelSqlGenerator>(Lifetime.Singleton, true);
     serviceRegistration.Register <IMssqlReadModelStore <TReadModel>, MssqlReadModelStore <TReadModel> >();
     serviceRegistration.Register <IReadModelStore <TReadModel> >(r => r.Resolver.Resolve <IMssqlReadModelStore <TReadModel> >());
 }
Example #29
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="context"></param>
        public void Start(IBundleContext context)
        {
            var serviceRef = context.GetServiceReference <IAttachContent>();

            AttachContentService = context.GetService <IAttachContent>(serviceRef);

            serviceRegistration = context.RegisterService <IMenuItemEvent>(new MenuItemEvent());
        }
 /// <summary>
 /// Gets a value which indicates whether or not the current provider has a specified registrations.
 /// </summary>
 /// <returns>
 /// <c>true</c>, if the registration is contained within this provider, <c>false</c> otherwise.</returns>
 /// <param name="registration">A registration.</param>
 public bool HasRegistration(IServiceRegistration registration)
 {
     if (registration == null)
     {
         throw new ArgumentNullException(nameof(registration));
     }
     return(providers.Any(x => x.HasRegistration(registration)));
 }
        /// <summary>
        /// Adds or updates an element in the repository.
        /// </summary>
        /// <param name="typeKey">The key type.</param>
        /// <param name="registration">The registration.</param>
        /// <param name="nameKey">The name of the registration.</param>
        public void AddOrUpdateRegistration(Type typeKey, IServiceRegistration registration, string nameKey)
        {
            var immutableTree = ImmutableTree<IServiceRegistration>.Empty;
            var newTree = immutableTree.AddOrUpdate(nameKey.GetHashCode(), registration);

            lock (this.syncObject)
            {
                this.serviceRepository = this.serviceRepository.AddOrUpdate(typeKey.GetHashCode(), newTree, (oldValue, newValue) => newValue);
            }
        }
Example #32
0
        public override void Start(IBundleContext context)
        {
            TestIBll.IMessage message = new TestBll.MessageBll();
            Message = message;

            TestIBll.ISayYear year = new TestBll.SayYearBll();
            SayYear = year;
            messageReg = context.RegisterService<TestIBll.IMessage>(message, null);
            sayyear = context.RegisterService<TestIBll.ISayYear>(year, null);

            mcontext = context;
        }
Example #33
0
 public override void Start(IBundleContext context)
 {
     IBLL.IMyBll mybll = new BLL.MyBll();
        mybllserver=context.RegisterService<IBLL.IMyBll>(mybll, null);
        mcontext = context;
 }
        public void UnpublishService(IBundleContext context, IServiceRegistration serviceRegistration)
        {
            // Remove the ServiceRegistration from the list of Services published by BundleContext.
            List<IServiceRegistration> contextServices = (List<IServiceRegistration>)publishedServicesByContext[context];
            if (contextServices != null)
            {
                contextServices.Remove(serviceRegistration);
            }

            // Remove the ServiceRegistration from the list of Services published by Class Name.
            string[] clazzes = ((ServiceRegistration)serviceRegistration).Classes;
            int size = clazzes.Length;

            for (int i = 0; i < size; i++)
            {
                string clazz = clazzes[i];
                List<IServiceRegistration> services = (List<IServiceRegistration>)publishedServicesByClass[clazz];
                services.Remove(serviceRegistration);
            }

            // Remove the ServiceRegistration from the list of all published Services.
            allPublishedServices.Remove(serviceRegistration);
        }
        public void PublishService(IBundleContext context, IServiceRegistration serviceRegistration)
        {
            // Add the ServiceRegistration to the list of Services published by BundleContext.
            List<IServiceRegistration> contextServices = null;
            if (publishedServicesByContext.ContainsKey(context))
            {
                contextServices = (List<IServiceRegistration>)publishedServicesByContext[context];
            }
            if (contextServices == null)
            {
                contextServices = new List<IServiceRegistration>();
                publishedServicesByContext.Add(context, contextServices);
            }
            contextServices.Add(serviceRegistration);

            // Add the ServiceRegistration to the list of Services published by Class Name.
            string[] clazzes = ((ServiceRegistration)serviceRegistration).Classes;
            int size = clazzes.Length;

            for (int i = 0; i < size; i++)
            {
                string clazz = clazzes[i];

                List<IServiceRegistration> services = null;
                if (publishedServicesByClass.ContainsKey(clazz))
                {
                    services = (List<IServiceRegistration>)publishedServicesByClass[clazz];
                }

                if (services == null)
                {
                    services = new List<IServiceRegistration>();
                    publishedServicesByClass.Add(clazz, services);
                }

                services.Add(serviceRegistration);
            }

            // Add the ServiceRegistration to the list of all published Services.
            allPublishedServices.Add(serviceRegistration);
        }
        private bool TryGetByTypeKeyWithConditionsWithoutGenericDefinitionExtraction(TypeInformation typeInfo, out IServiceRegistration registration)
        {
            ImmutableTree<IServiceRegistration> registrations;
            if (!this.TryGetRegistrationsByTypeWithoutGenericDefinitionExtraction(typeInfo.Type, out registrations))
            {
                registration = null;
                return false;
            }

            var serviceRegistrations = registrations.Enumerate().Select(reg => reg.Value).ToArray();
            if (serviceRegistrations.Any(reg => reg.HasCondition))
                registration = serviceRegistrations.Where(reg => reg.HasCondition)
                                                   .FirstOrDefault(reg => reg.IsUsableForCurrentContext(typeInfo));
            else
                registration = serviceRegistrations.FirstOrDefault(reg => reg.IsUsableForCurrentContext(typeInfo));

            return registration != null;
        }
        private bool TryGetByTypeKey(TypeInformation typeInfo, out IServiceRegistration registration)
        {
            ImmutableTree<IServiceRegistration> registrations;
            if (!this.TryGetRegistrationsByType(typeInfo.Type, out registrations))
            {
                registration = null;
                return false;
            }

            registration = registrations.Value;
            return true;
        }
        private bool TryGetByNamedKeyWithoutGenericDefinitionExtraction(TypeInformation typeInfo, out IServiceRegistration registration)
        {
            ImmutableTree<IServiceRegistration> registrations;
            if (this.TryGetRegistrationsByTypeWithoutGenericDefinitionExtraction(typeInfo.Type, out registrations))
            {
                registration = registrations.GetValueOrDefault(typeInfo.DependencyName.GetHashCode());
                return registration != null;
            }

            registration = null;
            return false;
        }
        /// <summary>
        /// Tries to retrieve all registrations for a type.
        /// </summary>
        /// <param name="typeInfo">The requested type information.</param>
        /// <param name="registrations">The retrieved registrations.</param>
        /// <returns>True if registrations were found, otherwise false.</returns>
        public bool TryGetTypedRepositoryRegistrations(TypeInformation typeInfo, out IServiceRegistration[] registrations)
        {
            var serviceRegistrations = this.serviceRepository.GetValueOrDefault(typeInfo.Type.GetHashCode());
            if (serviceRegistrations == null)
            {
                Type genericTypeDefinition;
                if (this.TryHandleOpenGenericType(typeInfo.Type, out genericTypeDefinition))
                {
                    serviceRegistrations = this.genericDefinitionRepository.GetValueOrDefault(genericTypeDefinition.GetHashCode());
                }
                else
                {
                    registrations = null;
                    return false;
                }
            }

            registrations = serviceRegistrations?.Enumerate().Select(reg => reg.Value).ToArray();
            return registrations != null;
        }
 /// <summary>
 /// Tries to retrieve a non generic definition registration with conditions.
 /// </summary>
 /// <param name="typeInfo">The requested type information.</param>
 /// <param name="registration">The retrieved registration.</param>
 /// <returns>True if a registration was found, otherwise false.</returns>
 public bool TryGetRegistrationWithConditionsWithoutGenericDefinitionExtraction(TypeInformation typeInfo, out IServiceRegistration registration)
 {
     return typeInfo.DependencyName == null ? this.TryGetByTypeKeyWithConditionsWithoutGenericDefinitionExtraction(typeInfo, out registration) :
         this.TryGetByNamedKeyWithoutGenericDefinitionExtraction(typeInfo, out registration);
 }
 /// <summary>
 /// Tries to retrieve a registration with conditions.
 /// </summary>
 /// <param name="typeInfo">The requested type information.</param>
 /// <param name="registration">The retrieved registration.</param>
 /// <returns>True if a registration was found, otherwise false.</returns>
 public bool TryGetRegistrationWithConditions(TypeInformation typeInfo, out IServiceRegistration registration)
 {
     return typeInfo.DependencyName == null ? this.TryGetByTypeKeyWithConditions(typeInfo, out registration) : this.TryGetByNamedKey(typeInfo, out registration);
 }
Example #42
0
 public override void Start(IBundleContext context)
 {
     Log2Service.ITextLog log = new Log2Net.TextLog();
     mybllserver = context.RegisterService<Log2Service.ITextLog>(log, null);
     mcontext = context;
 }