public IEnumerable <IComponentRegistration> RegistrationsFor(Service service,
                                                                 Func <Service, IEnumerable <IComponentRegistration> > registrationAccessor)
    {
        IServiceWithType serviceWithType = service as IServiceWithType;

        if (serviceWithType == null || !serviceWithType.ServiceType.IsGenericType)
        {
            yield break;
        }
        if (serviceWithType.ServiceType.GetGenericTypeDefinition() != typeof(Func <>))
        {
            yield break;
        }
        Type       elementType         = serviceWithType.ServiceType.GetGenericArguments()[0];
        Type       fixedFactoryType    = typeof(FixedFactory <>).MakeGenericType(elementType);
        Service    fixedFactoryService = serviceWithType.ChangeType(fixedFactoryType);
        MethodInfo getInstanceMethod   = typeof(FixedFactory <>).MakeGenericType(elementType).GetMethod("GetInstance");

        foreach (IComponentRegistration registration in registrationAccessor(fixedFactoryService))
        {
            yield return(RegistrationBuilder.ForDelegate(typeof(Func <>).MakeGenericType(elementType), (c, p) =>
            {
                // /!\ disposal of this object is not managed
                Object fixedFactory = c.ResolveComponent(registration, p);
                return getInstanceMethod.CreateDelegate(typeof(Func <>)
                                                        .MakeGenericType(elementType), fixedFactory);
            })
                         .As(service)
                         .Targeting(registration)
                         .CreateRegistration());
        }
    }
Exemple #2
0
        static IComponentRegistration BuildRegistration <TSettings>() where TSettings : ISettings, new()
        {
            return(RegistrationBuilder
                   .ForDelegate((c, p) =>
            {
                int currentSiteId = 0;
                ISiteContext storeContext;
                if (c.TryResolve <ISiteContext>(out storeContext))
                {
                    var store = storeContext.CurrentSite;

                    currentSiteId = store.Id;
                    //uncomment the code below if you want load settings per store only when you have two stores installed.
                    //var currentSiteId = c.Resolve<ISiteService>().GetAllSites().Count > 1
                    //    c.Resolve<ISiteContext>().CurrentSite.Id : 0;

                    ////although it's better to connect to your database and execute the following SQL:
                    //DELETE FROM [Setting] WHERE [SiteId] > 0

                    return c.Resolve <ISettingService>().LoadSetting <TSettings>(currentSiteId);
                }

                // Unit tests
                return new TSettings();
            })
                   .InstancePerRequest()
                   .CreateRegistration());
        }
Exemple #3
0
        /// <summary>
        /// Registers aggregation decorator (decorator that will broadcast all calls to all decorated instances)
        /// for the services of type <typeparamref name="TService" />.
        /// </summary>
        /// <typeparam name="TService">Type of the decorated services.</typeparam>
        /// <param name="builder">Container builder.</param>
        /// <param name="decoratorFactory">Factory delegate that can create new instances of the aggregate decorator.</param>
        /// <returns>Registration builder to continue the registration.</returns>
        public static IRegistrationBuilder <TService, SimpleActivatorData, SingleRegistrationStyle> RegisterAggregationDecorator <TService>(
            this ContainerBuilder builder, Func <IComponentContext, IEnumerable <TService>, TService> decoratorFactory)
        {
            Guard.NotNull("builder", builder);
            Guard.NotNull("decoratorFactory", decoratorFactory);

            var originalKey         = Guid.NewGuid();
            var registrationBuilder = RegistrationBuilder.ForDelegate((c, p) => decoratorFactory(c, c.ResolveKeyed <IEnumerable <TService> >(originalKey))).As <TService>();

            builder.RegisterCallback(cr =>
            {
                Guard.NotNull("componentRegistry", cr);

                var service = new TypedService(typeof(TService));
                var originalRegistrations = cr.RegistrationsFor(service);

                // Register original component as keyed
                foreach (var originalRegistration in originalRegistrations)
                {
                    cr.Register(RegistrationBuilder.CreateRegistration(
                                    Guid.NewGuid(),
                                    CopyRegistrationData(originalRegistration),
                                    originalRegistration.Activator,
                                    new[] { new KeyedService(originalKey, typeof(TService)) }));
                }

                // Override default registration with decorator
                RegistrationBuilder.RegisterSingleComponent <TService, SimpleActivatorData, SingleRegistrationStyle>(cr, registrationBuilder);
            });

            return(registrationBuilder);
        }
        /// <summary>
        ///     Retrieve a registration for an unregistered service, to be used
        ///     by the container.
        /// </summary>
        /// <param name="service">The service that was requested.</param>
        /// <param name="registrationAccessor"></param>
        /// <returns>
        ///     Registrations for the service.
        /// </returns>
        public IEnumerable <IComponentRegistration> RegistrationsFor
            (Service service, Func <Service, IEnumerable <IComponentRegistration> > registrationAccessor)
        {
            if (service == null)
            {
                throw new ArgumentNullException(nameof(service));
            }

            if (!(service is IServiceWithType typedService) ||
                !typedService.ServiceType.IsInterface ||
                IsGenericListOrCollectionInterface(typedService.ServiceType) ||
                (typedService.ServiceType.IsGenericType && typedService.ServiceType.GetGenericTypeDefinition() == typeof(IPipelineBehavior <,>)) ||
                typedService.ServiceType.IsArray ||
                typeof(IStartable).IsAssignableFrom(typedService.ServiceType))
            {
                return(Enumerable.Empty <IComponentRegistration>());
            }

            var registrations          = registrationAccessor(service);
            var componentRegistrations = registrations as IComponentRegistration[] ?? registrations.ToArray();

            if (componentRegistrations.Any())
            {
                return(componentRegistrations);
            }

            var rb = RegistrationBuilder.ForDelegate((c, p) => Substitute.For(new[] { typedService.ServiceType }, null))
                     .As(service)
                     .InstancePerLifetimeScope();

            return(new[] { rb.CreateRegistration() });
        }
        /// <summary>
        /// Retrieve registrations for an unregistered service, to be used by the container.
        /// </summary>
        /// <param name="service">The service that was requested.</param>
        /// <param name="registrationAccessor">A function that will return existing registrations for a service.</param>
        public IEnumerable <IComponentRegistration> RegistrationsFor(Service service, Func <Service, IEnumerable <IComponentRegistration> > registrationAccessor)
        {
            // There are other registration exists in the container
            if (registrationAccessor(service).Any())
            {
                return(Enumerable.Empty <IComponentRegistration>());
            }

            var swt = service as IServiceWithType;

            if (swt == null)
            {
                return(Enumerable.Empty <IComponentRegistration>());
            }

            object instance = CMS.Core.Service.ResolveOptional(swt.ServiceType);

            if (instance == null)
            {
                return(Enumerable.Empty <IComponentRegistration>());
            }

            // Register the instance in the container
            return(new[] { RegistrationBuilder.ForDelegate(swt.ServiceType, (c, p) => instance).CreateRegistration() });
        }
Exemple #6
0
        /// <summary>
        /// Retrieve registrations for an unregistered service, to be used
        /// by the container.
        /// </summary>
        /// <param name="service">The service that was requested.</param>
        /// <param name="registrationAccessor">A function that will return existing registrations for a service.</param>
        /// <returns>Registrations providing the service.</returns>
        /// <remarks>
        /// If the source is queried for service s, and it returns a component that implements both s and s', then it
        /// will not be queried again for either s or s'. This means that if the source can return other implementations
        /// of s', it should return these, plus the transitive closure of other components implementing their
        /// additional services, along with the implementation of s. It is not an error to return components
        /// that do not implement <paramref name="service" />.
        /// </remarks>
        public IEnumerable <IComponentRegistration> RegistrationsFor(Service service, Func <Service, IEnumerable <ServiceRegistration> > registrationAccessor)
        {
            var swt = service as IServiceWithType;

            if (swt == null || !swt.ServiceType.IsGenericType)
            {
                yield break;
            }

            var def = swt.ServiceType.GetGenericTypeDefinition();

            if (def != typeof(DbSet <>))
            {
                yield break;
            }

            // if you have one `IDBContext` registeration you don't need the
            // foreach over the registrationAccessor(dbContextServices)

            yield return(RegistrationBuilder.ForDelegate((c, p) =>
            {
                var dBContext = c.Resolve <TContext>();
                var m = dBContext.GetType().GetMethod(nameof(DbContext.Set), new Type[] { });
                var method =
                    m.MakeGenericMethod(swt.ServiceType.GetGenericArguments());
                return method.Invoke(dBContext, null);
            })
                         .As(service)
                         .CreateRegistration());
        }
Exemple #7
0
 static IComponentRegistration BuildRegistration <TSettings>() where TSettings : ISettings, new()
 {
     return(RegistrationBuilder
            .ForDelegate((c, p) => c.Resolve <IConfigurationProvider <TSettings> >().Settings)
            .InstancePerHttpRequest()
            .CreateRegistration());
 }
        /// <summary>
        ///     Retrieve a registration for an unregistered service, to be used
        ///     by the container.
        /// </summary>
        /// <param name="service">The service that was requested.</param>
        /// <param name="registrationAccessor"></param>
        /// <returns>
        ///     Registrations for the service.
        /// </returns>
        public IEnumerable <IComponentRegistration> RegistrationsFor
            (Service service, Func <Service, IEnumerable <IComponentRegistration> > registrationAccessor)
        {
            if (service == null)
            {
                throw new ArgumentNullException("service");
            }

            var typedService = service as IServiceWithType;

            if (typedService == null ||
                !typedService.ServiceType.IsInterface ||
                IsGenericListOrCollectionInterface(typedService.ServiceType) ||
                typedService.ServiceType.IsArray ||
                typeof(IStartable).IsAssignableFrom(typedService.ServiceType))
            {
                return(Enumerable.Empty <IComponentRegistration>());
            }

            var rb = RegistrationBuilder.ForDelegate((c, p) => Substitute.For(new[] { typedService.ServiceType }, null))
                     .As(service)
                     .InstancePerLifetimeScope();

            return(new[] { rb.CreateRegistration() });
        }
Exemple #9
0
 private static IComponentRegistration BuildRegistration <TSettings>() where TSettings : ISettings, new()
 {
     return(RegistrationBuilder
            .ForDelegate((c, p) => { return c.Resolve <ISettingService>().LoadSetting <TSettings>(); })
            .InstancePerLifetimeScope()
            .CreateRegistration());
 }
        /// <summary>
        /// Retrieve a registration for an unregistered service, to be used
        /// by the container.
        /// </summary>
        /// <param name="service">The service that was requested.</param>
        /// <param name="registrationAccessor"></param>
        /// <returns>
        /// Registrations for the service.
        /// </returns>
        public IEnumerable <IComponentRegistration> RegistrationsFor
            (Service service, Func <Service, IEnumerable <IComponentRegistration> > registrationAccessor)
        {
            if (service == null)
            {
                throw new ArgumentNullException("service");
            }

            var typedService = service as IServiceWithType;

            if (typedService == null ||
                !typedService.ServiceType.IsInterface() ||
                typedService.ServiceType.IsGenericType() &&
                typedService.ServiceType.GetGenericTypeDefinition() == typeof(IEnumerable <>) ||
                typedService.ServiceType.IsArray ||
                typedService.ServiceType.CanBeCastTo <IStartable>())
            {
                return(Enumerable.Empty <IComponentRegistration>());
            }

            var rb = RegistrationBuilder.ForDelegate <object>((c, p) => _mockFactory.CreateMock(typedService.ServiceType))
                     .As(service)
                     .InstancePerLifetimeScope();

            return(new[] { rb.CreateRegistration() });
        }
Exemple #11
0
        static IComponentRegistration BuildRegistration <TSettings>() where TSettings : ISettings, new()
        {
            try
            {
                return(RegistrationBuilder
                       .ForDelegate((c, p) =>
                {
                    //var currentsiteId = c.Resolve<ISiteContext>().CurrentSite.Id;
                    var currentsiteId = 1;
                    //uncomment the code below if you want load settings per site only when you have two sites installed.
                    //var currentsiteId = c.Resolve<IsiteService>().GetAllsites().Count > 1
                    //    c.Resolve<IsiteContext>().Currentsite.Id : 0;

                    //although it's better to connect to your database and execute the following SQL:
                    //DELETE FROM [Setting] WHERE [siteId] > 0
                    return c.Resolve <ISettingService>().LoadSetting <TSettings>(currentsiteId);
                })
                       .InstancePerLifetimeScope()
                       .CreateRegistration());
            }
            catch (Exception ex)
            {
                return(null);
            }
        }
Exemple #12
0
    public IEnumerable <IComponentRegistration> RegistrationsFor(
        Service service,
        Func <Service, IEnumerable <IComponentRegistration> > registrationAccessor)
    {
        var swt = service as IServiceWithType;

        if (swt == null)
        {
            yield break;
        }
        var existingReg = registrationAccessor(service);

        if (existingReg.Any())
        {
            yield break;
        }
        var reg = RegistrationBuilder.ForDelegate((c, p) =>
        {
            var createMethod =
                typeof(MockFactory).GetMethod("Create", Type.EmptyTypes).MakeGenericMethod(swt.ServiceType);
            return(((Mock)createMethod.Invoke(this.MockFactory, null)).Object);
        }).As(swt.ServiceType).CreateRegistration();

        yield return(reg);
    }
Exemple #13
0
    public IEnumerable <IComponentRegistration> RegistrationsFor(Service service, Func <Service, IEnumerable <IComponentRegistration> > registrationAccessor)
    {
        IServiceWithType typedService = service as IServiceWithType;

        if (typedService == null)
        {
            return(Enumerable.Empty <IComponentRegistration>());
        }
        if (!(typedService.ServiceType.IsGenericType && typedService.ServiceType.GetGenericTypeDefinition() == typeof(IEnumerable <>)))
        {
            return(Enumerable.Empty <IComponentRegistration>());
        }
        Type    elementType    = typedService.ServiceType.GetGenericArguments()[0];
        Service elementService = typedService.ChangeType(elementType);
        Type    collectionType = typeof(List <>).MakeGenericType(elementType);
        IComponentRegistration registration = RegistrationBuilder.ForDelegate(collectionType, (c, p) =>
        {
            IEnumerable <IComponentRegistration> registrations = c.ComponentRegistry.RegistrationsFor(elementService);
            IEnumerable <Object> elements = registrations.Select(cr => c.ResolveComponent(cr, p));
            // get distinct elements by type
            Array array  = elements.GroupBy(o => o.GetType()).Select(o => o.First()).ToArray();
            Array array2 = Array.CreateInstance(elementType, array.Length);
            array.CopyTo(array2, 0);
            Object collection = Activator.CreateInstance(collectionType, new Object[] { array2 });
            return(collection);
        }).As(service)
                                              .CreateRegistration();

        return(new IComponentRegistration[] { registration });
    }
        /// <summary>
        /// Retrieve registrations for an unregistered service, to be used
        /// by the container.
        /// </summary>
        /// <param name="service">The service that was requested.</param>
        /// <param name="registrationAccessor">A function that will return existing registrations for a service.</param>
        /// <returns>Registrations providing the service.</returns>
        public IEnumerable <IComponentRegistration> RegistrationsFor(Service service, Func <Service, IEnumerable <IComponentRegistration> > registrationAccessor)
        {
            var seenRegistrations = new HashSet <IComponentRegistration>();
            var seenServices      = new HashSet <Service>();
            var lastRunServices   = new List <Service> {
                service
            };

            while (lastRunServices.Any())
            {
                var nextService = lastRunServices.First();
                lastRunServices.Remove(nextService);
                seenServices.Add(nextService);
                foreach (var registration in _registry.RegistrationsFor(nextService).Where(r => !r.IsAdapting()))
                {
                    if (seenRegistrations.Contains(registration))
                    {
                        continue;
                    }

                    seenRegistrations.Add(registration);
                    lastRunServices.AddRange(registration.Services.Where(s => !seenServices.Contains(s)));

                    var r = registration;
                    yield return(RegistrationBuilder.ForDelegate(r.Activator.LimitType, (c, p) => c.ResolveComponent(r, p))
                                 .Targeting(r)
                                 .As(r.Services.ToArray())
                                 .ExternallyOwned()
                                 .CreateRegistration());
                }
            }
        }
Exemple #15
0
    public IEnumerable <IComponentRegistration> RegistrationsFor(Service service,
                                                                 Func <Service, IEnumerable <IComponentRegistration> > registrationAccessor)
    {
        // there are other registration exists in the container
        if (registrationAccessor(service).Any())
        {
            return(Enumerable.Empty <IComponentRegistration>());
        }

        var swt = service as IServiceWithType;

        if (swt == null)
        {
            return(Enumerable.Empty <IComponentRegistration>());
        }

        // try to get an instance from the IServiceProvider
        var instance = serviceProvider.GetService(swt.ServiceType);

        if (instance == null)
        {
            return(Enumerable.Empty <IComponentRegistration>());
        }

        // register the instance in the container
        return(new[]
        {
            RegistrationBuilder.ForDelegate(swt.ServiceType,
                                            (c, p) => instance)
            .CreateRegistration()
        });
    }
Exemple #16
0
        private void RegisterServices(ContainerBuilder builder, IServiceCollection services)
        {
            ServiceRegistrationActionList actionList = null;
            var serviceDescriptor = services.FirstOrDefault(d => d.ServiceType == typeof(ServiceRegistrationActionList));

            if (serviceDescriptor != null)
            {
                actionList = (ServiceRegistrationActionList)serviceDescriptor.ImplementationInstance;
            }
            if (actionList == null)
            {
                actionList = new ServiceRegistrationActionList();
                services.AddSingleton(actionList);
            }

            foreach (var service in services)
            {
                if (service.ImplementationType != null)
                {
                    // Test if the an open generic type is being registered
                    var serviceTypeInfo = service.ServiceType.GetTypeInfo();
                    if (serviceTypeInfo.IsGenericTypeDefinition)
                    {
                        builder
                        .RegisterGeneric(service.ImplementationType)
                        .As(service.ServiceType)
                        .ConfigureLifecycle(service.Lifetime)
                        .ConfigureConventions(actionList);
                    }
                    else
                    {
                        builder
                        .RegisterType(service.ImplementationType)
                        .As(service.ServiceType)
                        .ConfigureLifecycle(service.Lifetime)
                        .ConfigureConventions(actionList);
                    }
                }
                else if (service.ImplementationFactory != null)
                {
                    var registration = RegistrationBuilder.ForDelegate(service.ServiceType, (context, parameters) =>
                    {
                        var serviceProvider = context.Resolve <IServiceProvider>();
                        return(service.ImplementationFactory(serviceProvider));
                    })
                                       .ConfigureLifecycle(service.Lifetime)
                                       .CreateRegistration();
                    //TODO: ConfigureAbpConventions ?

                    builder.RegisterComponent(registration);
                }
                else
                {
                    builder
                    .RegisterInstance(service.ImplementationInstance)
                    .As(service.ServiceType)
                    .ConfigureLifecycle(service.Lifetime);
                }
            }
        }
        static IComponentRegistration CreateMetaRegistration <T>(Service providedService, IComponentRegistration valueRegistration) where T : class
        {
            var rb = RegistrationBuilder.ForDelegate(
                (c, p) => {
                var workContextAccessor = c.Resolve <IWorkContextAccessor>();
                return(new Work <T>(w => {
                    var workContext = workContextAccessor.GetContext();
                    if (workContext == null)
                    {
                        return default(T);
                    }

                    var workValues = workContext.Resolve <WorkValues <T> >();

                    T value;
                    if (!workValues.Values.TryGetValue(w, out value))
                    {
                        value = (T)workValues.ComponentContext.ResolveComponent(valueRegistration, p);
                        workValues.Values[w] = value;
                    }
                    return value;
                }));
            })
                     .As(providedService)
                     .Targeting(valueRegistration);

            return(rb.CreateRegistration());
        }
 /// <summary>
 /// Helper method to return registrations.
 /// </summary>
 /// <typeparam name="TService"></typeparam>
 /// <returns></returns>
 static IComponentRegistration CreateOrderedRegistration <TService>()
 {
     return(RegistrationBuilder
            .ForDelegate((c, ps) => c.ResolveOrdered <TService>(ps))
            .ExternallyOwned()
            .CreateRegistration());
 }
        public IEnumerable <IComponentRegistration> RegistrationsFor
            (Service service, Func <Service, IEnumerable <IComponentRegistration> > registrationAccessor)
        {
            if (service == null)
            {
                throw new ArgumentNullException("service");
            }

            var typedService = service as TypedService;

            if (typedService == null ||
                !typedService.ServiceType.IsInterface ||
                typedService.ServiceType.IsGenericType && typedService.ServiceType.GetGenericTypeDefinition() == typeof(IEnumerable <>) ||
                typedService.ServiceType.IsArray ||
                typeof(IStartable).IsAssignableFrom(typedService.ServiceType))
            {
                return(Enumerable.Empty <IComponentRegistration>());
            }

            var rb = RegistrationBuilder.ForDelegate((c, p) => CreateMock(c, typedService))
                     .As(service)
                     .InstancePerLifetimeScope();

            return(new[] { rb.CreateRegistration() });
        }
Exemple #20
0
 static IComponentRegistration BuildRegistration<TSettings>()
         where TSettings : ISettings {
     return RegistrationBuilder
         .ForDelegate((c, p) =>
             c.Resolve<IConfigurationProvider<TSettings>>().Settings)
         .CreateRegistration();
 }
Exemple #21
0
        /// <summary>
        /// Retrieve registrations for an unregistered service, to be used
        /// by the container.
        /// </summary>
        /// <param name="service">The service that was requested.</param>
        /// <param name="registrationAccessor">A function that will return existing registrations for a service.</param>
        /// <returns>Registrations providing the service.</returns>
        public IEnumerable <IComponentRegistration> RegistrationsFor(Service service, Func <Service, IEnumerable <IComponentRegistration> > registrationAccessor)
        {
            if (service == null)
            {
                throw new ArgumentNullException(nameof(service));
            }
            if (registrationAccessor == null)
            {
                throw new ArgumentNullException(nameof(registrationAccessor));
            }

            var ts = service as IServiceWithType;

            if (ts != null && ts.ServiceType.IsDelegate())
            {
                var resultType        = ts.ServiceType.FunctionReturnType();
                var resultTypeService = ts.ChangeType(resultType);

                return(registrationAccessor(resultTypeService)
                       .Select(r =>
                {
                    var factory = new FactoryGenerator(ts.ServiceType, r, ParameterMapping.Adaptive);
                    var rb = RegistrationBuilder.ForDelegate(ts.ServiceType, factory.GenerateFactory)
                             .InstancePerLifetimeScope()
                             .ExternallyOwned()
                             .As(service)
                             .Targeting(r);

                    return rb.CreateRegistration();
                }));
            }

            return(Enumerable.Empty <IComponentRegistration>());
        }
            IEnumerable<IComponentRegistration> IRegistrationSource.RegistrationsFor(
                Service service,
                Func<Service, IEnumerable<IComponentRegistration>> registrationAccessor) {

                var swt = service as IServiceWithType;
                if (swt == null)
                    yield break;
                var st = swt.ServiceType;

                if (st.IsGenericType && st.GetGenericTypeDefinition() == typeof(Mock<>)) {                    
                    yield return RegistrationBuilder.ForType(st)
                        .SingleInstance()
                        .WithParameter("behavior", _behavior)
                        .CreateRegistration();
                }
                else if (st.IsInterface) {
                    if (st.IsGenericType && st.GetGenericTypeDefinition() == typeof(IEnumerable<>)) {
                        yield break;
                    }
                    if (_ignore.Contains(st)) {
                        yield break;
                    }

                    yield return RegistrationBuilder.ForDelegate(
                        (ctx, p) => {
                            Trace.WriteLine(string.Format("Mocking {0}", st));
                            var mt = typeof(Mock<>).MakeGenericType(st);
                            var m = (Mock)ctx.Resolve(mt);
                            return m.Object;
                        })
                        .As(service)
                        .SingleInstance()
                        .CreateRegistration();
                }
            }
Exemple #23
0
 public static IComponentRegistration CreateSingletonRegistration <T>(T instance)
 {
     return(RegistrationBuilder
            .ForDelegate((c, p) => instance)
            .SingleInstance()
            .CreateRegistration());
 }
        public IEnumerable <IComponentRegistration> RegistrationsFor(Service service, Func <Service, IEnumerable <IComponentRegistration> > registrationAccessor)
        {
            var serviceWithType = service as IServiceWithType;

            if (serviceWithType == null)
            {
                yield break;
            }

            var serviceType = serviceWithType.ServiceType;

            if (!serviceType.IsInterface || !typeof(IEventHandler).IsAssignableFrom(serviceType) || serviceType == typeof(IEventHandler))
            {
                yield break;
            }

            var interfaceProxyType = _proxyBuilder.CreateInterfaceProxyTypeWithoutTarget(
                serviceType,
                new Type[0],
                ProxyGenerationOptions.Default);


            var rb = RegistrationBuilder
                     .ForDelegate((ctx, parameters) => {
                var interceptors = new IInterceptor[] { new EventsInterceptor(ctx.Resolve <IEventBus>()) };
                var args         = new object[] { interceptors, null };
                return(Activator.CreateInstance(interfaceProxyType, args));
            })
                     .As(service);

            yield return(rb.CreateRegistration());
        }
Exemple #25
0
        public IEnumerable <IComponentRegistration> RegistrationsFor(Service service, Func <Service, IEnumerable <IComponentRegistration> > registrationAccessor)
        {
            var typedService = service as TypedService;

            if (typedService == null ||
                typedService.ServiceType.IsGenericType && typedService.ServiceType.GetGenericTypeDefinition() == typeof(IEnumerable <>) ||
                typedService.ServiceType.IsArray ||
                typeof(IStartable).IsAssignableFrom(typedService.ServiceType))
            {
                yield break;
            }

            if (typedService.ServiceType == this.ResolvedType)
            {
                foreach (var reg in concretesSource.RegistrationsFor(service, registrationAccessor))
                {
                    yield return(reg);
                }
            }
            else
            {
                var rb = RegistrationBuilder.ForDelegate((c, p) => CreateMock(c, typedService))
                         .As(service)
                         .InstancePerLifetimeScope();

                yield return(rb.CreateRegistration());
            }
        }
Exemple #26
0
        /// <summary>
        /// Retrieve registrations for an unregistered service, to be used
        /// by the container.
        /// </summary>
        /// <param name="service">The service that was requested.</param>
        /// <param name="registrationAccessor">A function that will return existing registrations for a service.</param>
        /// <returns>Registrations providing the service.</returns>
        public IEnumerable <IComponentRegistration> RegistrationsFor(
            Service service, Func <Service, IEnumerable <IComponentRegistration> > registrationAccessor)
        {
            if (registrationAccessor == null)
            {
                throw new ArgumentNullException(nameof(registrationAccessor));
            }

            var typedService = service as TypedService;

            if (typedService == null || typedService.ServiceType == typeof(string))
            {
                return(Enumerable.Empty <IComponentRegistration>());
            }

            var typeInfo = typedService.ServiceType.GetTypeInfo();

            if (typedService.ServiceType == RelaxedAutoFakeCreator.SUTType ||
                (typeInfo.IsClass && typeInfo.IsAbstract) ||
                typeInfo.IsInterface ||
                (typeInfo.IsGenericType && typedService.ServiceType.GetGenericTypeDefinition() == typeof(IEnumerable <>)) ||
                typedService.ServiceType.IsArray ||
                registrationAccessor(service).Any() ||
                !(typeInfo.DeclaredMethods.Any(x => x.IsVirtual) || typeInfo.DeclaredProperties.Any(x =>
                                                                                                    x.GetMethod?.IsVirtual != true || x.SetMethod?.IsVirtual != true)))
            {
                return(Enumerable.Empty <IComponentRegistration>());
            }

            var rb = RegistrationBuilder.ForDelegate((c, p) => this.CreateFake(typedService))
                     .As(service)
                     .InstancePerLifetimeScope();

            return(new[] { rb.CreateRegistration() });
        }
Exemple #27
0
        public IEnumerable <IComponentRegistration> RegistrationsFor(Service service, Func <Service, IEnumerable <IComponentRegistration> > registrationAccessor)
        {
            if (service == null)
            {
                throw new ArgumentNullException("service");
            }
            if (registrationAccessor == null)
            {
                throw new ArgumentNullException("registrationAccessor");
            }

            if (_registrationData.Services.Contains(service))
            {
                return(registrationAccessor(_activatorData.FromService)
                       .Select(r =>
                {
                    var rb = RegistrationBuilder
                             .ForDelegate((c, p) => _activatorData.Adapter(c, p, c.ResolveComponent(service, r, Enumerable.Empty <Parameter>())))
                             .Targeting(r);

                    rb.RegistrationData.CopyFrom(_registrationData, true);

                    return rb.CreateRegistration();
                }));
            }

            return(new IComponentRegistration[0]);
        }
        /// <summary>
        /// Retrieves registration for an unregistered service that is to be used by the container.
        /// </summary>
        /// <param name="service">The service that was requested.</param>
        /// <param name="registrationAccessor">A function that returns existing registrations for a service.</param>
        public IEnumerable <IComponentRegistration> RegistrationsFor(Service service, Func <Service, IEnumerable <IComponentRegistration> > registrationAccessor)
        {
            // Checks if the container already contains an existing registration for the requested service
            if (registrationAccessor(service).Any())
            {
                return(Enumerable.Empty <IComponentRegistration>());
            }
            // Checks if the required service carries valid type information
            if (!(service is IServiceWithType swt))
            {
                return(Enumerable.Empty <IComponentRegistration>());
            }

            // Gets an instance of the requested service using CMS.Core.API
            object instance = null;

            if (CMS.Core.Service.IsRegistered(swt.ServiceType))
            {
                instance = CMS.Core.Service.Resolve(swt.ServiceType);
            }

            if (instance == null)
            {
                return(Enumerable.Empty <IComponentRegistration>());
            }

            // Registers the service instance in the container
            return(new[] { RegistrationBuilder.ForDelegate(swt.ServiceType, (c, p) => instance).CreateRegistration() });
        }
Exemple #29
0
        /// <summary>
        /// Retrieve a registration for an unregistered service, to be used
        /// by the container.
        /// </summary>
        /// <param name="service">The service that was requested.</param>
        /// <param name="registrationAccessor"></param>
        /// <returns>
        /// Registrations for the service.
        /// </returns>
        public IEnumerable <IComponentRegistration> RegistrationsFor
            (Service service, Func <Service, IEnumerable <IComponentRegistration> > registrationAccessor)
        {
            if (service == null)
            {
                throw new ArgumentNullException("service");
            }

            var typedService = service as TypedService;

            if (typedService == null ||
                !typedService.ServiceType.IsInterface ||
                typeof(IEnumerable).IsAssignableFrom(typedService.ServiceType) ||
                typeof(IStartable).IsAssignableFrom(typedService.ServiceType))
            {
                return(Enumerable.Empty <IComponentRegistration>());
            }

            var rb = RegistrationBuilder.ForDelegate((c, p) =>
            {
                var specificCreateMethod =
                    _createMethod.MakeGenericMethod(new[] { typedService.ServiceType });
                var mock = (Mock)specificCreateMethod.Invoke(c.Resolve <MockRepository>(), null);
                return(mock.Object);
            })
                     .As(service)
                     .InstancePerLifetimeScope();

            return(new[] { rb.CreateRegistration() });
        }
Exemple #30
0
        public IEnumerable <IComponentRegistration> RegistrationsFor(Service service, Func <Service, IEnumerable <IComponentRegistration> > registrationAccessor)
        {
            if (registrationAccessor(service).Any())
            {
                return(Enumerable.Empty <IComponentRegistration>());
            }

            if (!(service is IServiceWithType swt))
            {
                return(Enumerable.Empty <IComponentRegistration>());
            }

            object instance = null;

            if (CMS.Core.Service.IsRegistered(swt.ServiceType))
            {
                instance = CMS.Core.Service.Resolve(swt.ServiceType);
            }

            if (instance == null)
            {
                return(Enumerable.Empty <IComponentRegistration>());
            }

            return(new[]
            {
                RegistrationBuilder.ForDelegate(swt.ServiceType, (c, p) => instance).CreateRegistration()
            });
        }