Beispiel #1
0
        /// <summary>
        ///
        /// </summary>
        public MultiEfRepository()
        {
            Type t = typeof(T);

            lock (t)
            {
                Service service = null;
                if (s_EntityKeyedServices.ContainsKey(t))
                {
                    service = s_EntityKeyedServices[t];
                }
                else
                {
                    var contextKeyAttribute = t.GetCustomAttribute <EntityContextKeyAttribute>();
                    if (contextKeyAttribute == null || contextKeyAttribute.ContextKey.IsEmpty())
                    {
                        service = new TypedService(t);
                    }
                    else
                    {
                        service = new KeyedService(contextKeyAttribute.ContextKey, t);
                    }
                    s_EntityKeyedServices.Add(t, service);
                }
                _context = EngineContext.Current.ContainerManager.ResolveService <IChenyuanDBContext>(service);
            }
        }
Beispiel #2
0
        private Func <object> GetFactory(Type type)
        {
            BuildScopeIfRequired();

            Func <object> factory;

            if (!SimpleCache.TryGetValue(type, out factory) &&
                !ServiceCache.TryGetValue(type, out factory))
            {
                var serv = new TypedService(type);
                IComponentRegistration reg;
                var inContainer = CurrentScope.ComponentRegistry.TryGetRegistration(serv, out reg);
                RegistrationCache.TryAdd(type, inContainer);
                if (inContainer)
                {
                    factory = CurrentScope.ResolveLookup(serv, reg, new Parameter[0]).Factory;
                    SimpleCache.TryAdd(type, factory);
                }
                else
                {
                    factory = BuildFactoryForService(type);
                    ServiceCache.TryAdd(type, factory);
                }
            }
            return(factory);
        }
        RegisterCollection <T>(ContainerBuilder builder, string collectionName, Type elementType)
        {
            if (builder == null)
            {
                throw new ArgumentNullException("builder");
            }
            if (elementType == null)
            {
                throw new ArgumentNullException("elementType");
            }
            Enforce.ArgumentNotNullOrEmpty(collectionName, "collectionName");

            var arrayType = elementType.MakeArrayType();
            var ts        = new TypedService(elementType);

            var activator = new DelegateActivator(arrayType, (c, p) =>
            {
                var elements = GetElementRegistrations(collectionName, c.ComponentRegistry);
                var items    = elements.Select(e => c.ResolveComponent(ts, e, p)).ToArray();

                var result = Array.CreateInstance(elementType, items.Length);
                items.CopyTo(result, 0);
                return(result);
            });

            var rb = new RegistrationBuilder <T[], SimpleActivatorData, SingleRegistrationStyle>(
                new TypedService(typeof(T[])),
                new SimpleActivatorData(activator),
                new SingleRegistrationStyle());

            builder.RegisterCallback(cr => RegistrationBuilder.RegisterSingleComponent(cr, rb));

            return(rb);
        }
Beispiel #4
0
        public void AfterResolvingAdapter_AddingMoreAdaptees_AddsMoreAdapters()
        {
            var registryBuilder = Factory.CreateEmptyComponentRegistryBuilder();

            registryBuilder.AddRegistrationSource(new MetaRegistrationSource());
            var metaService = new TypedService(typeof(Meta <object>));

            var first = RegistrationBuilder.ForType <object>().CreateRegistration();

            registryBuilder.Register(first);

            using (var container = new Container(registryBuilder.Build()))
            {
                var meta1 = container.ComponentRegistry.RegistrationsFor(metaService);
                Assert.Single(meta1);

                var second = RegistrationBuilder.ForType <object>().CreateRegistration();

                using (var lifetimeScope = container.BeginLifetimeScope(builder => builder.ComponentRegistryBuilder.Register(second)))
                {
                    var meta2 = lifetimeScope.ComponentRegistry.RegistrationsFor(metaService);

                    Assert.Equal(2, meta2.Count());
                }
            }
        }
Beispiel #5
0
        public void IgnoresTypesThatShouldNotBeProvided(Type serviceType)
        {
            var source  = new AnyConcreteTypeNotAlreadyRegisteredSource();
            var service = new TypedService(serviceType);

            Assert.False(source.RegistrationsFor(service, s => Enumerable.Empty <IComponentRegistration>()).Any(), $"Failed: {serviceType}");
        }
Beispiel #6
0
        /// <summary>
        /// Creates the controller.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="controllerType">Type of the controller.</param>
        /// <returns>The controller.</returns>
        protected override IController GetControllerInstance(RequestContext context, Type controllerType)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            // a null controller type is a 404, because the base class couldn't resolve the controller name back to a type
            // a common example of this case would be a non-existant favicon.ico
            if (controllerType == null)
            {
                throw new HttpException(404,
                                        string.Format("controller type was not found for path {0}",
                                                      context.HttpContext.Request.Path));
            }

            var controllerService = new TypedService(controllerType);

            object controller;

            if (_containerProvider.RequestLifetime.TryResolveService(controllerService, out controller))
            {
                return((IController)controller);
            }

            throw new HttpException(404,
                                    string.Format(AutofacControllerFactoryResources.NotFound,
                                                  controllerService,
                                                  controllerType.FullName,
                                                  context.HttpContext.Request.Path));
        }
Beispiel #7
0
        private object CreateMock(IComponentContext context, TypedService typedService)
        {
            var mock = Mock.Create(typedService.ServiceType);

            this.mocks.Add(mock);
            return(mock);
        }
        /// <summary>
        /// Creates a mock object.
        /// </summary>
        /// <param name="context">The component context.</param>
        /// <param name="typedService">The typed service.</param>
        /// <returns>
        /// The mock object from the repository.
        /// </returns>
        private object CreateMock(IComponentContext context, TypedService typedService)
        {
            var specificCreateMethod = this._createMethod.MakeGenericMethod(new[] { typedService.ServiceType });
            var mock = (Mock)specificCreateMethod.Invoke(context.Resolve <MockRepository>(), null);

            return(mock.Object);
        }
Beispiel #9
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);
        }
Beispiel #10
0
        public void ChangeType_ProvidesTypedServiceWithNewType()
        {
            var nt = typeof(string);
            var ts = new TypedService(typeof(object));
            var n  = ts.ChangeType(nt);

            Assert.Equal(new TypedService(nt), n);
        }
Beispiel #11
0
            public void SetUp()
            {
                _modelMapper = new ModelMapper();
                TypeModel unused;

                _modelMapper.GetOrAddTypeModel(typeof(string), out unused);
                _service = new TypedService(typeof(string));
                _mapped  = _modelMapper.GetServiceModel(_service);
            }
Beispiel #12
0
        private static Service AddSelfTypedService <THandler, TActivatorData>(
            IRegistrationBuilder <THandler, TActivatorData, SingleRegistrationStyle> rb, Type handlerType = null)
        {
            var service = new TypedService(handlerType ?? typeof(THandler));

            rb.RegistrationData.AddService(service);

            return(service);
        }
Beispiel #13
0
        public static void InjectProperties(IComponentContext context, object instance, IPropertySelector propertySelector)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }
            if (instance == null)
            {
                throw new ArgumentNullException(nameof(instance));
            }
            if (propertySelector == null)
            {
                throw new ArgumentNullException(nameof(propertySelector));
            }

            var instanceType = instance.GetType();

            foreach (var property in instanceType
                     .GetRuntimeProperties()
                     .Where(pi => pi.CanWrite))
            {
                var propertyType = property.PropertyType;

                if (propertyType.GetTypeInfo().IsValueType&& !propertyType.GetTypeInfo().IsEnum)
                {
                    continue;
                }

                if (propertyType.IsArray && propertyType.GetElementType().GetTypeInfo().IsValueType)
                {
                    continue;
                }

                if (propertyType.IsGenericEnumerableInterfaceType() && propertyType.GetTypeInfo().GenericTypeArguments[0].GetTypeInfo().IsValueType)
                {
                    continue;
                }

                if (property.GetIndexParameters().Length != 0)
                {
                    continue;
                }

                if (!propertySelector.InjectProperty(property, instance))
                {
                    continue;
                }

                object propertyValue;
                var    propertyService       = new TypedService(propertyType);
                var    instanceTypeParameter = new NamedParameter(InstanceTypeNamedParameter, instanceType);
                if (context.TryResolveService(propertyService, new Parameter[] { instanceTypeParameter }, out propertyValue))
                {
                    property.SetValue(instance, propertyValue, null);
                }
            }
        }
        public IEnumerable <IComponentRegistration> RegistrationsFor(Service service, Func <Service, IEnumerable <ServiceRegistration> > registrationAccessor)
        {
            var objectService = new TypedService(typeof(object));

            if (service == objectService)
            {
                yield return(Factory.CreateSingletonObjectRegistration(_instance));
            }
        }
Beispiel #15
0
        /// <summary>
        /// 装配字段
        /// </summary>
        /// <param name="property"></param>
        /// <param name="context"></param>
        /// <param name="Parameters"></param>
        /// <param name="instance"></param>
        /// <param name="allowCircle"></param>
        /// <returns></returns>
        public object ResolveField(FieldInfo property, IComponentContext context, IEnumerable <Parameter> Parameters, object instance, bool allowCircle)
        {
            if (!allowCircle)
            {
                return(property == null ? null : Resolve(property.DeclaringType, property.FieldType, context, "field"));
            }
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }
            if (instance == null)
            {
                throw new ArgumentNullException(nameof(instance));
            }


            Service propertyService = null;

            if (!string.IsNullOrEmpty(this.Name))
            {
                propertyService = new KeyedService(this.Name, property.FieldType);
            }
            else
            {
                propertyService = new TypedService(property.FieldType);
            }

            if (Parameters != null && Parameters.Count() == 1)
            {
                if (!(Parameters.First() is AutowiredParmeter AutowiredParmeter))
                {
                    return(null);
                }
                if (AutowiredParmeter.AutowiredChains.TryGetValue(property.FieldType.FullName, out var objectInstance))
                {
                    return(objectInstance);
                }
                else
                {
                    AutowiredParmeter.Add(property.DeclaringType.FullName, instance);
                    if (context.TryResolveService(propertyService, new Parameter[] { AutowiredParmeter }, out var propertyValue))
                    {
                        return(propertyValue);
                    }
                }
            }
            else
            {
                var instanceTypeParameter = new AutowiredParmeter();
                instanceTypeParameter.Add(property.DeclaringType.FullName, instance);
                if (context.TryResolveService(propertyService, new Parameter[] { instanceTypeParameter }, out var propertyValue))
                {
                    return(propertyValue);
                }
            }
            return(null);
        }
 public IRegistrationBuilder As(Type type)
 {
     if (type == null)
     {
         throw new ArgumentNullException(nameof(type));
     }
     Service = new TypedService(type);
     return(this);
 }
        static IEnumerable <Parameter> AddDecoratedComponentParameter(Type decoratedParameterType, IComponentRegistration decoratedComponent, IEnumerable <Parameter> configuredParameters)
        {
            var ts        = new TypedService(decoratedParameterType);
            var parameter = new ResolvedParameter(
                (pi, c) => pi.ParameterType == decoratedParameterType,
                (pi, c) => c.ResolveComponent(ts, decoratedComponent, Enumerable.Empty <Parameter>()));

            return(new[] { parameter }.Concat(configuredParameters));
        }
Beispiel #18
0
        /// <summary>
        /// Inject properties onto an instance, filtered by a property selector.
        /// </summary>
        /// <param name="context">The component context to resolve dependencies from.</param>
        /// <param name="instance">The instance to inject onto.</param>
        /// <param name="propertySelector">The property selector.</param>
        /// <param name="parameters">The set of parameters for the resolve that can be used to satisfy injectable properties.</param>
        public static void InjectProperties(IComponentContext context, object instance, IPropertySelector propertySelector, IEnumerable <Parameter> parameters)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (instance == null)
            {
                throw new ArgumentNullException(nameof(instance));
            }

            if (propertySelector == null)
            {
                throw new ArgumentNullException(nameof(propertySelector));
            }

            if (parameters == null)
            {
                throw new ArgumentNullException(nameof(parameters));
            }

            var resolveParameters = parameters as Parameter[] ?? parameters.ToArray();

            var instanceType         = instance.GetType();
            var injectableProperties = InjectableProperties.GetOrAdd(instanceType, type => GetInjectableProperties(type).ToArray());

            for (var index = 0; index < injectableProperties.Length; index++)
            {
                var property = injectableProperties[index];

                if (!propertySelector.InjectProperty(property, instance))
                {
                    continue;
                }

                // SetMethod will be non-null if GetInjectableProperties included it.
                var setParameter  = property.SetMethod !.GetParameters()[0];
                var valueProvider = (Func <object?>?)null;
                var parameter     = resolveParameters.FirstOrDefault(p => p.CanSupplyValue(setParameter, context, out valueProvider));
                if (parameter != null)
                {
                    var setter = PropertySetters.GetOrAdd(property, MakeFastPropertySetter);
                    setter(instance, valueProvider !());
                    continue;
                }

                var propertyService       = new TypedService(property.PropertyType);
                var instanceTypeParameter = new NamedParameter(InstanceTypeNamedParameter, instanceType);
                if (context.TryResolveService(propertyService, new Parameter[] { instanceTypeParameter }, out var propertyValue))
                {
                    var setter = PropertySetters.GetOrAdd(property, MakeFastPropertySetter);
                    setter(instance, propertyValue);
                }
            }
        }
Beispiel #19
0
        static void StartStartableComponents(IComponentContext componentContext)
        {
            var ts = new TypedService(typeof(IStartable));

            foreach (var startable in componentContext.ComponentRegistry.RegistrationsFor(ts))
            {
                var instance = (IStartable)componentContext.ResolveComponent(ts, startable, Enumerable.Empty <Parameter>());
                instance.Start();
            }
        }
        public IEnumerable <IComponentRegistration> RegistrationsFor(Service service, Func <Service, IEnumerable <IComponentRegistration> > registrationAccessor)
        {
            TypedService service2 = service as TypedService;

            if ((((service2 == null) || !service2.ServiceType.IsClass) || (service2.ServiceType.IsSubclassOf(typeof(Delegate)) || service2.ServiceType.IsAbstract)) || (!this._predicate(service2.ServiceType) || registrationAccessor(service).Any <IComponentRegistration>()))
            {
                return(Enumerable.Empty <IComponentRegistration>());
            }
            return(new IComponentRegistration[] { RegistrationBuilder.ForType(service2.ServiceType).CreateRegistration <object, ConcreteReflectionActivatorData, SingleRegistrationStyle>() });
        }
        internal object Resolve(IComponentContext context, object instance, Type classType, Type memberType, IEnumerable <Parameter> Parameters)
        {
            if ((typeof(IObjectFactory).IsAssignableFrom(memberType)))
            {
                return(context.Resolve <ObjectBeanFactory>().CreateAutowiredFactory(this, memberType, classType, instance, Parameters));
            }

            Service propertyService = null;

            if (!string.IsNullOrEmpty(this.Name))
            {
                propertyService = new KeyedService(this.Name, memberType);
            }
            else
            {
                propertyService = new TypedService(memberType);
            }

            // ReSharper disable once PossibleMultipleEnumeration
            if (Parameters != null && Parameters.Count() == 1)
            {
                // ReSharper disable once PossibleMultipleEnumeration
                if (!(Parameters.First() is AutowiredParmeter AutowiredParmeter))
                {
                    return(null);
                }

                // ReSharper disable once AssignNullToNotNullAttribute
                if (AutowiredParmeter.TryGet(getAutowiredParmeterKey(memberType), out var objectInstance))
                {
                    return(objectInstance);
                }
                else
                {
                    // ReSharper disable once PossibleNullReferenceException
                    AutowiredParmeter.TryAdd(getAutowiredParmeterKey(classType), instance);
                    if (context.TryResolveService(propertyService, new Parameter[] { AutowiredParmeter }, out var propertyValue))
                    {
                        return(propertyValue);
                    }
                }
            }
            else
            {
                var instanceTypeParameter = new AutowiredParmeter();
                // ReSharper disable once PossibleNullReferenceException
                instanceTypeParameter.TryAdd(getAutowiredParmeterKey(classType), instance);
                if (context.TryResolveService(propertyService, new Parameter[] { instanceTypeParameter }, out var propertyValue))
                {
                    return(propertyValue);
                }
            }

            return(null);
        }
        public void ServiceEquality(Type dependencyType, object ownedKey, Type ownedType, bool expected)
        {
            var dependencyService   = new TypedService(dependencyType);
            var instancePerOwnedKey = new InstancePerOwnedKey(dependencyService);

            var ownedService = ownedKey != null
                ? (IServiceWithType) new KeyedService(ownedKey, ownedType)
                : new TypedService(ownedType);

            Assert.Equal(expected, instancePerOwnedKey.Equals(ownedService));
        }
Beispiel #23
0
        private static ResolveRequestContext MockResolveRequestContext()
        {
            var service      = new TypedService(typeof(string));
            var activator    = Mock.Of <IInstanceActivator>(act => act.LimitType == typeof(string));
            var registration = Mock.Of <IComponentRegistration>(reg => reg.Activator == activator);

            return(Mock.Of <ResolveRequestContext>(
                       ctx =>
                       ctx.Service == service &&
                       ctx.Registration == registration));
        }
		public void InjectProperties(IComponentContext context, object instance, bool overrideSetValues)
		{
			if (context == null) throw new ArgumentNullException("context");
			if (instance == null) throw new ArgumentNullException("instance");

			var instanceType = instance.GetType();

			foreach (var property in instanceType.GetProperties(
				BindingFlags.Public | BindingFlags.Instance | BindingFlags.SetProperty))
			{
				var propertyType = property.PropertyType;

				if (propertyType.IsValueType && !propertyType.IsEnum)
					continue;

				if (property.GetIndexParameters().Length != 0)
					continue;

				if (!context.IsRegistered(propertyType))
					continue;

				var accessors = property.GetAccessors(false);
				if (accessors.Length == 1 && accessors[0].ReturnType != typeof(void))
					continue;

				if (!overrideSetValues &&
					accessors.Length == 2 &&
					(property.GetValue(instance, null) != null))
					continue;

				IComponentRegistration registration;
				var service = new TypedService(propertyType);
				if (!context.ComponentRegistry.TryGetRegistration(service, out registration))
					throw new ComponentNotRegisteredException(service);

				var lookup = context.ResolveLookup(service, registration, Enumerable.Empty<Parameter>());
				try
				{
					if (lookup.Preparing)
						lookup.SharedInstanceActivation += (s, ea) => property.SetValue(instance, s, null);
					else
					{
						var propertyValue = lookup.Factory();
						property.SetValue(instance, propertyValue, null);
					}
				}
				catch (DependencyResolutionException dre)
				{
					dre.Lookups.Push(lookup);
					throw;
				}
			}
		}
        /// <summary>
        /// Add a handler for the Activated event.
        /// </summary>
        /// <param name="handler">The event handler.</param>
        /// <returns>A registration builder allowing further configuration of the component.</returns>
        public IRegistrationBuilder <TLimit, TActivatorData, TRegistrationStyle> OnActivated(Action <IActivatedEventArgs <TLimit> > handler)
        {
            if (handler == null)
            {
                throw new ArgumentNullException("handler");
            }
            var ts = new TypedService(typeof(TLimit));

            RegistrationData.ActivatedHandlers.Add(
                (s, e) => handler(new ActivatedEventArgs <TLimit>(ts, e.Context, e.Component, e.Parameters, (TLimit)e.Instance)));
            return(this);
        }
Beispiel #26
0
        public void SingletonsRegisteredDirectlyAreWrappedWithLifetimeDecorator()
        {
            var registry = new ScopeRestrictedRegistry(new object(), new Dictionary <string, object>());

            registry.Register(ObjectRegistration);

            var typedService = new TypedService(typeof(object));

            registry.TryGetRegistration(typedService, out IComponentRegistration registration);

            Assert.IsType <ComponentRegistrationLifetimeDecorator>(registration);
        }
        public IRegistrationBuilder As <TService>()
        {
            #region Please modify the code to pass the test

            /*
             * Please support registration by type.
             */
            Service = new TypedService(typeof(TService));
            return(this);

            #endregion
        }
        public void CheckServicesShouldOnlyHaveDependenciesWithLesserLifetime(AutofacRegistrations data)
        {
            var exceptions = new List <string>();

            foreach (var registration in data.ComponentRegistry.Registrations)
            {
                var registrationLifetime = data.GetLifetime(registration);

                foreach (var ctorParameter in data.GetRegistrationConstructorParameters(registration))
                {
                    var typedService = new TypedService(ctorParameter.ParameterType);

                    if (ContainsMicrosoftInNamespace(typedService.ServiceType))
                    {
                        continue;
                    }

                    if (ContainsSystemInNamespace(typedService.ServiceType))
                    {
                        continue;
                    }

                    // If the parameter is not registered with autofac, ignore
                    if (!data.ComponentRegistry.TryGetRegistration(typedService, out var parameterRegistration))
                    {
                        continue;
                    }

                    var parameterLifetime = data.GetLifetime(parameterRegistration);

                    if (parameterLifetime >= registrationLifetime)
                    {
                        continue;
                    }

                    var typeName      = data.GetConcreteType(registration).ToString();
                    var parameterType = ctorParameter.ParameterType.ToString();

                    var error = $"{typeName} ({registrationLifetime}) => {parameterType} ({parameterLifetime})";
                    exceptions.Add(error);
                }
            }

            if (exceptions.Any())
            {
                throw new Exception("The following components should not depend on with greater lifetimes: " +
                                    $"{exceptions.Aggregate((a, b) => a + Environment.NewLine + b)}");
            }

            bool ContainsMicrosoftInNamespace(Type type) => type.Assembly.FullName.StartsWith("Microsoft", StringComparison.InvariantCultureIgnoreCase);
            bool ContainsSystemInNamespace(Type type) => type.Assembly.FullName.StartsWith("System", StringComparison.InvariantCultureIgnoreCase);
        }
        protected virtual void OnContainerConfigured(IComponentRegistry registry)
        {
            var service = new TypedService(typeof(ITransportMessages));

            registry.RegistrationsFor(service).First().Activated += (s, e) =>
            {
                var subscriber = e.Context.Resolve <ISubscribeToMessages>();
                foreach (var request in this.requests)
                {
                    subscriber.Subscribe(request.Key, null, request.Value.ToArray());
                }
            };
        }
        public void WhenRegistrationsAreMadeTheyDoNotAffectTheReadRegistry()
        {
            var read         = new ComponentRegistry();
            var cow          = new CopyOnWriteRegistry(read, () => new ComponentRegistry());
            var registration = RegistrationBuilder.ForType <object>().CreateRegistration();

            cow.Register(registration);

            var objectService = new TypedService(typeof(object));

            Assert.True(cow.IsRegistered(objectService));
            Assert.False(read.IsRegistered(objectService));
        }
Beispiel #31
0
        public void WhenAdaptersAreAppliedButNoRegistrationsCreated_AddingAdapteesAddsAdapters()
        {
            var registry = new ComponentRegistry();

            registry.AddRegistrationSource(new GeneratedFactoryRegistrationSource());
            var adapterService = new TypedService(typeof(Func <object>));

            registry.RegistrationsFor(adapterService);
            registry.Register(RegistrationBuilder.ForType <object>().CreateRegistration());
            var adapters = registry.RegistrationsFor(adapterService);

            Assert.AreEqual(1, adapters.Count());
        }
Beispiel #32
0
		/// <summary>
		/// Returns true if the parameter is able to provide a value to a particular site.
		/// </summary>
		/// <param name="pi">Constructor, method, or property-mutator parameter.</param>
		/// <param name="context">The component context in which the value is being provided.</param>
		/// <param name="valueProvider">If the result is true, the valueProvider parameter will
		/// be set to a function that will lazily retrieve the parameter value. If the result is false,
		/// will be set to null.</param>
		/// <returns>True if a value can be supplied; otherwise, false.</returns>
		public override bool CanSupplyValue(ParameterInfo pi, IComponentContext context, out Func<object> valueProvider)
		{
			IComponentRegistration registration;
			var ts = new TypedService(pi.ParameterType);
			if (context.ComponentRegistry.TryGetRegistration(ts, out registration))
			{
				var lookup = context.ResolveLookup(ts, registration, Enumerable.Empty<Parameter>());
				try
				{
					valueProvider = lookup.Factory;
				}
				catch (DependencyResolutionException dre)
				{
					dre.Lookups.Push(lookup);
					throw;
				}
				return true;
			}
			valueProvider = null;
			return false;
		}
		static IEnumerable<Parameter> AddDecoratedComponentParameter(Type decoratedParameterType, IComponentRegistration decoratedComponent, IEnumerable<Parameter> configuredParameters)
		{
			var ts = new TypedService(decoratedParameterType);
			var parameter = new ResolvedParameter(
				(pi, c) => pi.ParameterType == decoratedParameterType,
				(pi, c) => c.ResolveComponent(ts, decoratedComponent, Enumerable.Empty<Parameter>()));

			return new[] { parameter }.Concat(configuredParameters);
		}
Beispiel #34
0
 static void StartStartableComponents(IComponentContext componentContext)
 {
     var ts = new TypedService(typeof(IStartable));
     foreach (var startable in componentContext.ComponentRegistry.RegistrationsFor(ts))
     {
         var instance = (IStartable)componentContext.ResolveComponent(ts, startable, Enumerable.Empty<Parameter>());
         instance.Start();
     }
 }
Beispiel #35
0
		private Func<object> GetFactory(Type type)
		{
			BuildScopeIfRequired();

			Func<object> factory;
			if (!SimpleCache.TryGetValue(type, out factory)
				&& !ServiceCache.TryGetValue(type, out factory))
			{
				var serv = new TypedService(type);
				IComponentRegistration reg;
				var inContainer = CurrentScope.ComponentRegistry.TryGetRegistration(serv, out reg);
				RegistrationCache.TryAdd(type, inContainer);
				if (inContainer)
				{
					factory = CurrentScope.ResolveLookup(serv, reg, new Parameter[0]).Factory;
					SimpleCache.TryAdd(type, factory);
				}
				else
				{
					factory = BuildFactoryForService(type);
					ServiceCache.TryAdd(type, factory);
				}
			}
			return factory;
		}
Beispiel #36
0
		public object Resolve(Type type, object[] args)
		{
			BuildScopeIfRequired();

			if (args == null)
			{
				Func<object> factory;
				if (!SimpleCache.TryGetValue(type, out factory))
				{
					var serv = new TypedService(type);
					IComponentRegistration reg;
					var inContainer = CurrentScope.ComponentRegistry.TryGetRegistration(serv, out reg);
					RegistrationCache.TryAdd(type, inContainer);
					if (inContainer)
						factory = CurrentScope.ResolveLookup(serv, reg, new Parameter[0]).Factory;
					else
						factory = () => BuildWithAspects(type)(null);
					SimpleCache.TryAdd(type, factory);
				}
				return factory();
			}
			else
			{
				Func<object[], object> factory;
				if (!CacheWithArguments.TryGetValue(type, out factory))
				{
					var serv = new TypedService(type);
					IComponentRegistration reg;
					var inContainer = CurrentScope.ComponentRegistry.TryGetRegistration(serv, out reg);
					RegistrationCache.TryAdd(type, inContainer);
					if (inContainer)
						factory = a => CurrentScope.ResolveLookup(serv, reg, a.Select(it => new TypedParameter(it.GetType(), it))).Factory();
					else
						factory = BuildWithAspects(type);
					CacheWithArguments.TryAdd(type, factory);
				}
				return factory(args);
			}
		}