/// <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 #2
0
        /// <summary>
        /// Since the last registration is considered the active one, when overriding previous registrations
        /// use this function to verify if the previous plugins are already registered and will be overriden.
        ///
        /// To force the specific registration order between modules (derivations of Autofac.Module)
        /// use [ExportMetadata(MefProvider.DependsOn, typeof(the other Autofac.Module derivation))] attribute
        /// on the module that registers the components that override registrations from the other module.
        /// </summary>
        public static void CheckOverride <TInterface, TImplementation>(ContainerBuilder builder, params Type[] expectedPreviousPlugins)
        {
            builder.RegisterCallback(componentRegistry =>
            {
                var existingService       = new Autofac.Core.TypedService(typeof(TInterface));
                var existingRegistrations = componentRegistry.RegistrationsFor(existingService).Select(r => r.Activator.LimitType).ToList();

                var missingRegistration = expectedPreviousPlugins.Except(existingRegistrations).ToList();
                var excessRegistration  = existingRegistrations.Except(expectedPreviousPlugins).ToList();

                if (missingRegistration.Count > 0 || excessRegistration.Count > 0)
                {
                    string error = "Unexpected plugins while overriding '" + typeof(TInterface).Name + "' with '" + typeof(TImplementation).Name + "'.";

                    if (missingRegistration.Count > 0)
                    {
                        error += " The following plugins should have been previous registered in order to be overriden: "
                                 + string.Join(", ", missingRegistration.Select(r => r.Name)) + ".";
                    }

                    if (excessRegistration.Count > 0)
                    {
                        error += " The following plugins have been previous registered and whould be unintentionally overriden: "
                                 + string.Join(", ", excessRegistration.Select(r => r.Name)) + ".";
                    }

                    error += " Verify that the module registration is occurring in the right order: Use [ExportMetadata(MefProvider.DependsOn, typeof(other Autofac.Module implementation))], to make those registration will occur before this one.";

                    throw new FrameworkException(error);
                }
            });
        }
Beispiel #3
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 #4
0
        public override bool Equals(object obj)
        {
            TypedService service = obj as TypedService;

            if (service == null)
            {
                return(false);
            }
            return(this.ServiceType.IsCompatibleWith(service.ServiceType));
        }
 public void AfterResolvingAdapterType_AddingAnAdapter_AddsAdaptingComponents()
 {
     var registry = new ComponentRegistry();
     registry.Register(RegistrationBuilder.ForType<object>().CreateRegistration());
     var adapterService = new TypedService(typeof(Func<object>));
     var pre = registry.RegistrationsFor(adapterService);
     Assert.AreEqual(0, pre.Count());
     registry.AddRegistrationSource(new GeneratedFactoryRegistrationSource());
     var post = registry.RegistrationsFor(adapterService);
     Assert.AreEqual(1, post.Count());
 }
        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));
        }
        public void ConnectionRegistrationsAreExternallyOwned()
        {
            var builder = new ContainerBuilder();
            builder.RegisterPersistentConnections(Assembly.GetExecutingAssembly());
            var container = builder.Build();

            var service = new TypedService(typeof(TestConnection));
            IComponentRegistration registration;
            container.ComponentRegistry.TryGetRegistration(service, out registration);

            Assert.Equal(InstanceOwnership.ExternallyOwned, registration.Ownership);
        }
        public void HubRegistrationsAreExternallyOwned()
        {
            var builder = new ContainerBuilder();
            builder.RegisterHubs(Assembly.GetExecutingAssembly());
            var container = builder.Build();

            var service = new TypedService(typeof(TestHub));
            IComponentRegistration registration;
            container.ComponentRegistry.TryGetRegistration(service, out registration);

            Assert.That(registration.Ownership, Is.EqualTo(InstanceOwnership.ExternallyOwned));
        }
        private static void ScanAssembly(IComponentRegistry componentRegistry, Assembly assembly)
        {
            var types = assembly.GetTypes()
                .Where(type => (type.IsClass && !type.IsAbstract) && (!type.IsGenericTypeDefinition && !type.IsSubclassOf(typeof(Delegate))))
                .ToArray();

            foreach (var type in types)
            {
                var implementedInterfaces = GetImplementedInterfaces(type);
                if (!implementedInterfaces.Any())
                    continue;

                if (!HasMarkerAttribute(type))
                {
                    var interfaceName = "I" + type.Name;
                    if (implementedInterfaces.All(interfaceType => interfaceType.Name != interfaceName))
                        continue;
                }

                var typedService = new TypedService(type);
                var data = new RegistrationData(typedService);

                data.AddServices(
                    implementedInterfaces.Select(
                        t =>
                        {
                            if (t.FullName == null)
                            {
                                return new TypedService(t.GetGenericTypeDefinition());
                            }
                            return new TypedService(t);
                        }).ToArray());

                if (IsSingleInstancing(typedService.ServiceType))
                {
                    data.Sharing = InstanceSharing.Shared;
                    data.Lifetime = new RootScopeLifetime();
                }
                else if (IsInstancingPerLifetimeScope(typedService.ServiceType))
                {
                    data.Sharing = InstanceSharing.Shared;
                    data.Lifetime = new MatchingScopeLifetime(LifetimeScopeTags.RequestScope);
                }

                var registration = RegistrationBuilder.CreateRegistration(
                    Guid.NewGuid(), data, new ConcreteReflectionActivatorData(typedService.ServiceType).Activator, data.Services);

                componentRegistry.Register(registration);
            }
        }
        public void AddingConcreteImplementationWhenAdapterImplementationsExist_AddsChainedAdapters()
        {
            var registry = new ComponentRegistry();
            registry.AddRegistrationSource(new GeneratedFactoryRegistrationSource());
            registry.AddRegistrationSource(new MetaRegistrationSource());
            registry.Register(RegistrationBuilder.ForType<object>().CreateRegistration());

            var chainedService = new TypedService(typeof(Meta<Func<object>>));

            var pre = registry.RegistrationsFor(chainedService);
            Assert.AreEqual(1, pre.Count());

            Func<object> func = () => new object();
            registry.Register(RegistrationBuilder.ForDelegate((c, p) => func).CreateRegistration());

            var post = registry.RegistrationsFor(chainedService);
            Assert.AreEqual(2, post.Count());
        }
        /// <summary>
        /// Since the last registration is considered the active one, when overriding previous registrations
        /// use this function to verify if the previous plugins are already registered and will be overridden.
        ///
        /// To force the specific registration order between modules (derivations of Autofac.Module)
        /// use [ExportMetadata(MefProvider.DependsOn, typeof(the other Autofac.Module derivation))] attribute
        /// on the module that registers the components that override registrations from the other module.
        /// </summary>
        public void CheckOverride <TInterface, TImplementation>(params Type[] expectedPreviousPlugins)
        {
            _builder.RegisterCallback(componentRegistry =>
            {
                var existingService       = new Autofac.Core.TypedService(typeof(TInterface));
                var existingRegistrations = componentRegistry.RegistrationsFor(existingService).Select(r => r.Activator.LimitType).ToList();

                var missingRegistration = expectedPreviousPlugins.Except(existingRegistrations).ToList();
                var excessRegistration  = existingRegistrations.Except(expectedPreviousPlugins).ToList();

                // Backward compatibility for old plugins: Old command-line utilities and unit tests might expect
                // to override WcfWindowsUserInfo, but it is no longer used in that context.
                var ignoredMissing = missingRegistration.RemoveAll(registation => registation.FullName == "Rhetos.Security.WcfWindowsUserInfo");
                if (ignoredMissing > 0)
                {
                    _logger.Trace($"Expecting WcfWindowsUserInfo registered while overriding '{typeof(TInterface).Name}'" +
                                  $" with '{typeof(TImplementation).FullName}'. Error is ignored for backward compatibility," +
                                  $" WcfWindowsUserInfo is no longer used in context of command-line utilities or unit tests.");
                }

                if (missingRegistration.Count > 0 || excessRegistration.Count > 0)
                {
                    string error = "Unexpected plugins while overriding '" + typeof(TInterface).Name + "' with '" + typeof(TImplementation).Name + "'.";

                    if (missingRegistration.Count > 0)
                    {
                        error += " The following plugins should have been previous registered in order to be overridden: "
                                 + string.Join(", ", missingRegistration.Select(r => r.Name)) + ".";
                    }

                    if (excessRegistration.Count > 0)
                    {
                        error += " The following plugins have been previous registered and would be unintentionally overridden: "
                                 + string.Join(", ", excessRegistration.Select(r => r.Name)) + ".";
                    }

                    error += " Verify that the module registration is occurring in the right order: Use [ExportMetadata(MefProvider.DependsOn, typeof(other Autofac.Module implementation))], to make those registration will occur before this one.";

                    throw new FrameworkException(error);
                }
            });
        }
        public void RespectsExplicitInterchangeServices()
        {
            var builder = new ContainerBuilder();
            var catalog = new TypeCatalog(typeof(HasMultipleExports));

            var interchangeService1 = new TypedService(typeof(HasMultipleExportsBase));
            var interchangeService2 = new KeyedService("b", typeof(HasMultipleExports));
            var nonInterchangeService1 = new TypedService(typeof(HasMultipleExports));
            var nonInterchangeService2 = new KeyedService("a", typeof(HasMultipleExports));

            builder.RegisterComposablePartCatalog(catalog,
                interchangeService1,
                interchangeService2);

            var container = builder.Build();

            Assert.IsTrue(container.IsRegisteredService(interchangeService1));
            Assert.IsTrue(container.IsRegisteredService(interchangeService2));
            Assert.IsFalse(container.IsRegisteredService(nonInterchangeService1));
            Assert.IsFalse(container.IsRegisteredService(nonInterchangeService2));
        }
        public void AfterResolvingAdapter_AddingMoreAdaptees_AddsMoreAdapters()
        {
            var registry = new ComponentRegistry();
            registry.AddRegistrationSource(new MetaRegistrationSource());
            var metaService = new TypedService(typeof(Meta<object>));

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

            var meta1 = registry.RegistrationsFor(metaService);
            var firstMeta = meta1.First();

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

            var meta2 = registry.RegistrationsFor(metaService);

            Assert.That(meta2.Count(), Is.EqualTo(2));
            Assert.That(meta2.Contains(firstMeta));
            Assert.That(meta2.Select(m => m.Target), Is.EquivalentTo(new[] { first, second }));
        }
Beispiel #14
0
 public void SetUp()
 {
     _modelMapper = new ModelMapper();
     TypeModel unused;
     _modelMapper.GetOrAddTypeModel(typeof(string), out unused);
     _service = new TypedService(typeof(string));
     _mapped = _modelMapper.GetServiceModel(_service);
 }
 public IEnumerable<IComponentRegistration> RegistrationsFor(Service service, Func<Service, IEnumerable<IComponentRegistration>> registrationAccessor)
 {
     var objectService = new TypedService(typeof(object));
     if (service == objectService)
         yield return Factory.CreateSingletonObjectRegistration(_instance);
 }
 private object CreateMock(IComponentContext context, TypedService typedService)
 {
     var specificCreateMethod =
                 _createMethod.MakeGenericMethod(new[] { typedService.ServiceType });
     var mock = (Mock)specificCreateMethod.Invoke(context.Resolve<MockRepository>(), null);
     return mock.Object;
 }
 public void NestedLifetimeScopesMaintainServiceLimitTypes()
 {
     // Issue #365
     var cb = new ContainerBuilder();
     cb.RegisterType<Person>();
     var container = cb.Build();
     var service = new TypedService(typeof(Person));
     using (var unconfigured = container.BeginLifetimeScope())
     {
         IComponentRegistration reg = null;
         Assert.True(unconfigured.ComponentRegistry.TryGetRegistration(service, out reg), "The registration should have been found in the unconfigured scope.");
         Assert.Equal(typeof(Person), reg.Activator.LimitType);
     }
     using (var configured = container.BeginLifetimeScope(b => { }))
     {
         IComponentRegistration reg = null;
         Assert.True(configured.ComponentRegistry.TryGetRegistration(service, out reg), "The registration should have been found in the configured scope.");
         Assert.Equal(typeof(Person), reg.Activator.LimitType);
     }
 }
Beispiel #18
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);
            }
        }
 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, DateTime.MaxValue, request.Value.ToArray());
     };
 }
 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());
 }