Esempio n. 1
0
        public static string GetMappingAsString(this ContainerRegistration registration)
        {
            string regName, regType, mapTo, lifetime;

            var r = registration.RegisteredType;

            regType = r.Name + GetGenericArgumentsList(r);

            var m = registration.MappedToType;

            mapTo = m.Name + GetGenericArgumentsList(m);

            regName = registration.Name ?? "[default]";

            lifetime = registration.LifetimeManagerType.Name;
            if (mapTo != regType)
            {
                mapTo = " -> " + mapTo;
            }
            else
            {
                mapTo = string.Empty;
            }
            lifetime = lifetime.Substring(0, lifetime.Length - "LifetimeManager".Length);

            return(String.Format("+ {0}{1}  '{2}'  {3}", regType, mapTo, regName, lifetime));
        }
        public static string GetMappingAsString(this ContainerRegistration registration)
        {
            string regName, regType, mapTo, lifeTime;

            var r = registration.RegisteredType;

            regType = r.Name + getGenericArgumentsList(r);

            var m = registration.MappedToType;

            mapTo = m.Name + getGenericArgumentsList(m);

            regName = registration.Name ?? "[default]";

            lifeTime = registration.LifetimeManagerType.Name;

            if (mapTo != regType)
            {
                mapTo = $" -> {mapTo}";
            }
            else
            {
                mapTo = string.Empty;
            }

            lifeTime = lifeTime.Substring(0, lifeTime.Length - "LifeTimeManager".Length);

            return($"+ {regType}{mapTo} '{regName}' {lifeTime}");
        }
        /// <summary>
        /// Registers all types derived from a base type
        /// </summary>
        /// <typeparam name="T"></typeparam>
        public static void RegisterAllDerivedTypes <T>(this IUnityContainer container)
        {
            // if an object was already mapped to another type but is derived from the registering type, don't register a new instance
            // for it, but instead register the existing instance with the registering type
            List <ContainerRegistration> alreadyMappedTypes =
                container.Registrations.Where(registration => typeof(T).IsAssignableFrom(registration.MappedToType) &&
                                              registration.LifetimeManagerType == typeof(ContainerControlledLifetimeManager)).ToList();

            IEnumerable <Assembly> assemblyList = AssemblyUtility.GetAssemblies();

            // get all listener types
            List <List <Type> > derivedTypes =
                assemblyList.Select(assembly => assembly.GetTypes()
                                    .Where(t => typeof(T).IsAssignableFrom(t) && !t.IsInterface).ToList()).ToList();

            // register all listener types
            derivedTypes.ForEach(derivedTypeInnerList =>
                                 derivedTypeInnerList.ForEach(derivedType =>
            {
                ContainerRegistration existingRegistration = alreadyMappedTypes.FirstOrDefault(registration => registration.MappedToType == derivedType);
                if (existingRegistration != null)
                {
                    T resolved = (T)container.Resolve(existingRegistration.RegisteredType, existingRegistration.Name);
                    container.RegisterInstance <T>(string.IsNullOrEmpty(existingRegistration.Name) ? existingRegistration.RegisteredType.Name : existingRegistration.Name, resolved);
                }
                else
                {
                    container.RegisterType(typeof(T), derivedType, derivedType.FullName, new ContainerControlledLifetimeManager());
                }
            }));
        }
Esempio n. 4
0
        void ILocatorRegistryWithVerification.Verify()
        {
            foreach (var item in _registrations)
            {
                var count = item.Value.Count;

                for (int i = 0; i < count; i++)
                {
                    ContainerRegistration registration = item.Value[i];

                    // for GetAllInstances to work they must be named, except for last
                    string serviceKey = registration.ServiceKey ?? ((i + 1 == count) ? "" : nameof(DotNetStarter) + $"_{i}");

                    if (registration.ServiceInstance is object)
                    {
                        _container.RegisterInstance(registration.ServiceType, registration.ServiceInstance);
                    }
                    else if (registration.ServiceFactory is object)
                    {
                        _container.RegisterFallback((type, key) => type == registration.ServiceType, r => registration.ServiceFactory.Invoke(_container.GetInstance <ILocatorAmbient>().Current), ConvertLifetime(registration.Lifecycle));
                    }
                    else
                    {
                        _container.Register(registration.ServiceType, registration.ServiceImplementation, serviceKey, ConvertLifetime(registration.Lifecycle));
                    }
                }
            }

            _verified = true;
        }
Esempio n. 5
0
        private static string GetMappingAsString(ContainerRegistration registration)
        {
            // code from https://msdn.microsoft.com/en-us/library/dn178463(v=pandp.30).aspx

            var registeredType     = registration.RegisteredType;
            var registeredTypeName = registeredType.Name + UnityExtensions.GetGenericArgumentsList(registeredType);

            var mappedToType  = registration.MappedToType;
            var mapToTypeName = mappedToType.Name + UnityExtensions.GetGenericArgumentsList(mappedToType);

            var registrationName = registration.Name ?? "[default]";

            var lifetime = registration.LifetimeManagerType.Name;

            if (mapToTypeName != registeredTypeName)
            {
                mapToTypeName = $" -> {mapToTypeName}";
            }
            else
            {
                mapToTypeName = string.Empty;
            }

            return($"+ {registeredTypeName}{mapToTypeName}  '{registrationName}'  {lifetime}");
        }
        private IEnumerable <IApiMethodCall> RouteEntryPoint(ContainerRegistration apiEntryPoint)
        {
            try
            {
                //Get all methods
                MethodInfo[] methods = apiEntryPoint.MappedToType.GetMethods(BindingFlags.Instance | BindingFlags.Public);

                var gloabalFilters =
                    apiEntryPoint.MappedToType.GetCustomAttributes(typeof(ApiCallFilter), true).Cast <ApiCallFilter>().ToList();
                gloabalFilters.AddRange(apiEntryPoint.MappedToType.Assembly.GetCustomAttributes(typeof(ApiCallFilter), true).Cast <ApiCallFilter>());
                gloabalFilters.AddRange(Container.ResolveAll <ApiCallFilter>());//Add gloably registered filters

                return((from methodInfo in methods.Where(x => !x.IsConstructor)
                        let attr =
                            methodInfo.GetCustomAttributes(typeof(ApiAttribute), true).Cast <ApiAttribute>().FirstOrDefault()
                            let cache =
                                methodInfo.GetCustomAttributes(typeof(CacheAttribute), true).Cast <CacheAttribute>().
                                FirstOrDefault()
                                let filters = methodInfo.GetCustomAttributes(typeof(ApiCallFilter), true).Cast <ApiCallFilter>()
                                              let poll = methodInfo.GetCustomAttributes(typeof(PollAttribute), true).Cast <PollAttribute>().
                                                         FirstOrDefault()
                                                         where attr != null
                                                         select ToApiMethodCall(methodInfo, apiEntryPoint, attr, cache, poll, filters, gloabalFilters)).ToList());
            }
            catch (Exception err)
            {
                Log.Error(err, "Could not load apiEntryPoint {0}", apiEntryPoint.Name);
                return(Enumerable.Empty <IApiMethodCall>());
            }
        }
        public void Initialize()
        {
            var hostnames = new List <string> {
                "cork.nl", "www.cork.nl"
            };

            TargetApplication = new TargetApplication
            {
                CertificatePassword = "******",
                Hostnames           = hostnames
            };

            var container     = ContainerRegistration.SetupLightInjectContainer(TargetApplication);
            var configuration = container.GetInstance <IConfiguration>();

            AcmeClientService  = container.GetInstance <IAcmeClientService>();
            CertificateService = container.GetInstance <ICertificateService>();

            // Cleanup authorization files if they exist to make sure we start with a clean slate
            var basePath         = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, TargetApplication.Hostnames.First());
            var signerFile       = Path.Combine(basePath, configuration.SignerFilename);
            var registrationFile = Path.Combine(basePath, configuration.RegistrationFilename);

            if (File.Exists(signerFile))
            {
                File.Delete(signerFile);
            }

            if (File.Exists(registrationFile))
            {
                File.Delete(registrationFile);
            }
        }
Esempio n. 8
0
        private object DoGetInstance(ContainerRegistration registration, Type type, string name)
        {
            if (registration is TypeRegistration typeRegistration)
            {
                var implementedType = typeRegistration.TypeTo;
                if (typeRegistration.IsSingleton && this.IsSingletonCached(implementedType, name))
                {
                    var instance = this.GetSingletonFromCache(implementedType, name);
                    this.OnResolved(registration, instance);
                    return(instance);
                }
                else
                {
                    var instance = DoGetNewInstance(typeRegistration);
                    return(instance);
                }
            }
            else if (registration is InstanceRegistration instanceRegistration)
            {
                var instance = instanceRegistration.Instance;
                this.OnResolvedForRegistration(registration, instance);
                this.OnResolved(instanceRegistration, instance);
                return(instance);
            }
            else if (registration is FactoryRegistration factoryRegistration)
            {
                var instance = factoryRegistration.Factory();
                this.OnResolvedForRegistration(registration, instance);
                this.OnResolved(factoryRegistration, instance);
                return(instance);
            }

            throw new ResolutionFailedException("Unexpected ContainerRegistrationType");
        }
Esempio n. 9
0
        private void BuildUndocumented(ContainerRegistration apiEntryPointRegistration, IEnumerable <IApiMethodCall> apiMethodCalls)
        {
            var root = new MsDocEntryPoint
            {
                Name    = apiEntryPointRegistration.Name,
                Remarks = "This entry point doesn't have any documentation. This is generated automaticaly using metadata",
                Methods = (from methodCall in apiMethodCalls
                           select new MsDocEntryPointMethod
                {
                    Path = methodCall.FullPath,
                    HttpMethod = methodCall.HttpMethod,
                    FunctionName = GetFunctionName(methodCall.MethodCall.Name),
                    Authentification = methodCall.RequiresAuthorization,
                    Response = TryCreateResponce(methodCall, Container, null),
                    Params = (from methodParam in
                              methodCall.GetParams()
                              select new MsDocEntryPointMethodParams
                    {
                        Name = methodParam.Name,
                        Visible = true,
                        Type = GetParameterTypeRepresentation(methodParam.ParameterType),
                        Method =
                            GuesMethod(
                                methodParam.Name,
                                methodCall.RoutingUrl, methodCall.HttpMethod)
                    }
                              ).ToList()
                }
                           ).ToList()
            };

            Points.Add(root);
        }
        public void InspectorCanBeResolved()
        {
            var container = ContainerRegistration.Init();

            var inspector = container.GetInstance <LocalEngine>();

            Assert.That(inspector, Is.Not.Null);
        }
        public void RootCanBeResolved()
        {
            var container = ContainerRegistration.Init();

            var engine = container.GetInstance <GithubEngine>();

            Assert.That(engine, Is.Not.Null);
        }
        public void CommandsCanBeResolved(Type commandType)
        {
            var container = ContainerRegistration.Init();

            var command = container.GetInstance(commandType);

            Assert.That(command, Is.Not.Null);
        }
Esempio n. 13
0
        public void RootCanBeResolved()
        {
            var container = ContainerRegistration.Init();

            var engine = container.GetInstance <ICollaborationEngine>();

            Assert.That(engine, Is.Not.Null);
            Assert.That(engine, Is.TypeOf <CollaborationEngine>());
        }
Esempio n. 14
0
        private void AddRegistration(Type type, string name, ContainerRegistration registration)
        {
            if (!this.registrations.ContainsKey(type))
            {
                this.registrations[type] = new Dictionary <string, ContainerRegistration>();
            }

            this.registrations[type][name] = registration;
        }
Esempio n. 15
0
        private void RaiseRegistered(ContainerRegistration registration)
        {
            var context = new RegistrationEventArgs(registration);

            foreach (var handler in this.registered)
            {
                handler(this, context);
            }
        }
Esempio n. 16
0
        private void OnResolved(ContainerRegistration registration, object instance)
        {
            var context = new ResolutionEventArgs(registration, instance);

            foreach (var handler in this.resolved)
            {
                handler(this, context);
            }
        }
 public static IContainerRegistration ToContainerRegistration(this ContainerRegistration cr)
 {
     return(new UnityContainerRegistration
     {
         LifetimeManagerType = cr.LifetimeManagerType,
         MappedToType = cr.MappedToType,
         Name = cr.Name,
         RegisteredType = cr.RegisteredType
     });
 }
            public void Should_Set_Lifetime()
            {
                // Given
                var registration = new ContainerRegistration(typeof(CakeBuildLog));
                var builder      = new ContainerRegistrationBuilder <CakeBuildLog>(registration);

                // When
                builder.Transient();

                // Then
                Assert.False(registration.IsSingleton);
            }
            public void Should_Add_Registration_Type()
            {
                // Given
                var registration = new ContainerRegistration(typeof(CakeBuildLog));
                var builder      = new ContainerRegistrationBuilder <CakeBuildLog>(registration);

                // When
                builder.AsSelf();

                // Then
                Assert.Equal(1, registration.RegistrationTypes.Count);
                Assert.Equal(typeof(CakeBuildLog), registration.RegistrationTypes.First());
            }
        public void RegisterTypes_PerformedRegistrations_ReturnsResults()
        {
            var registrations = new ContainerRegistration[0];

            mappingHandler.Setup(mh => mh.PerformRegistrations(It.IsAny <IUnityContainer>(), It.IsAny <IEnumerable <TypeMapping> >()))
            .Returns(registrations);

            // Act
            var result = controller.RegisterTypes(MappingBehaviors.None);

            // Assert
            Assert.AreSame(registrations, result);
        }
Esempio n. 21
0
        protected BaseViewModelTests()
        {
            ContainerRegistration.Register(false);

            var routeMappings = TinyIoCContainer.Current.Resolve <IDictionary <Type, string> >();

            _navigationService = new FakeNavigationService(routeMappings);
            _messagingCenter   = new FakeMessagingCenter();
            _database          = new FakeDatabase();

            TinyIoCContainer.Current.Register <IDataStore <Item> >(new MockDataStore());
            TinyIoCContainer.Current.Register <IAmADatabase>(_database);
        }
Esempio n. 22
0
 private static void SetLifetime <TLimit, TActivatorData, TRegistrationStyle>(
     IRegistrationBuilder <TLimit, TActivatorData, TRegistrationStyle> builder,
     ContainerRegistration registration)
 {
     if (registration.IsSingleton)
     {
         builder.SingleInstance();
     }
     else
     {
         builder.InstancePerDependency();
     }
 }
Esempio n. 23
0
        private void AddRegistration(ContainerRegistration registration)
        {
            var service        = registration.ServiceType;
            var implementation = registration.ServiceInstance?.GetType() ?? registration.ServiceImplementation;

            RegistryExtensions.ConfirmService(service, implementation);

            if (!_registrations.TryGetValue(registration.ServiceType, out List <ContainerRegistration> storedTypes))
            {
                storedTypes = new List <ContainerRegistration>();
            }

            storedTypes.Add(registration);
            _registrations[registration.ServiceType] = storedTypes;
        }
Esempio n. 24
0
 private static void SetRegistrationTypes <TLimit, TActivatorData, TRegistrationStyle>(
     IRegistrationBuilder <TLimit, TActivatorData, TRegistrationStyle> builder,
     ContainerRegistration registration)
 {
     if (registration.RegistrationTypes.Count > 0)
     {
         foreach (var type in registration.RegistrationTypes)
         {
             builder.As(type);
         }
     }
     else
     {
         builder.As(registration.ImplementationType);
     }
 }
Esempio n. 25
0
        private string RegistrationType(ContainerRegistration registration)
        {
            switch (registration.Lifetime)
            {
            case Constants.ContainerRegistrationEvent.SingletonLifetime:
                return("AddSingleton");

            case Constants.ContainerRegistrationEvent.PerServiceCallLifetime:
                return("AddScoped");

            case Constants.ContainerRegistrationEvent.TransientLifetime:
                return("AddTransient");

            default:
                return("AddTransient");
            }
        }
Esempio n. 26
0
        public override void PreBuildUp(IBuilderContext context)
        {
            ContainerRegistration containerRegistration = context.Registration as ContainerRegistration;
            InternalRegistration  internalRegistration  = context.Registration as InternalRegistration;

            if (containerRegistration != null)
            {
                _log.Info($"Building {containerRegistration.RegisteredType.FullName} mapped to {containerRegistration.MappedToType.FullName}");
            }
            else if (internalRegistration != null)
            {
                _log.Info($"Building {internalRegistration.Type.FullName}");
            }
            else
            {
                _log.Info($"Building {context.BuildKey.Type.FullName}");
            }
        }
        private IApiMethodCall ToApiMethodCall(MethodInfo methodInfo, ContainerRegistration apiEntryPointType, ApiAttribute attr, CacheAttribute cache, IEnumerable <ApiCallFilter> filters, List <ApiCallFilter> gloabalFilters)
        {
            var methodCall = Container.Resolve <IApiMethodCall>();

            methodCall.MethodCall            = methodInfo;
            methodCall.Name                  = apiEntryPointType.Name;
            methodCall.ApiClassType          = apiEntryPointType.MappedToType;
            methodCall.HttpMethod            = attr.Method;
            methodCall.RoutingUrl            = ExtractPath(attr.Path);
            methodCall.CacheTime             = cache != null ? cache.CacheTime : 0;
            methodCall.Constraints           = ExtractConstraints(attr.Path, attr.Method);
            methodCall.RequiresAuthorization = attr.RequiresAuthorization;

            //Add filters
            gloabalFilters.AddRange(filters);
            methodCall.Filters = gloabalFilters;

            return(methodCall);
        }
Esempio n. 28
0
        public IEnumerable <CSharpClassMember> Generate(ContainerRegistration registration)
        {
            var methodReg = registration as ContainerRegistrationMethod;

            if (methodReg == null)
            {
                return(new CSharpClassMember[0]);
            }

            var members = new List <CSharpClassMember>();

            if (methodReg.Lifetime == LifetimeScope.Singleton)
            {
                members.AddRange(CreateSingletons(methodReg));
            }
            else
            {
                members.Add(CreateTransients(methodReg));
            }

            return(members);
        }
Esempio n. 29
0
        public void Validate(ContainerFactory factory, ContainerRegistration registration, IList <string> errors)
        {
            var direct = registration as ContainerRegistrationDirect;

            if (direct == null)
            {
                return;
            }

            if (!registration.Binding.IsAssignableFrom(direct.Implementation))
            {
                errors.Add($"Registration resolving `{direct.Binding.GetRightFullName()}` "
                           + $"not assingable from `{direct.Implementation.GetRightFullName()}`");
                return;
            }

            var ctor = direct.Implementation
                       .GetConstructors()
                       .OrderBy(c => c.GetParameters()
                                .Count())
                       .First();

            var dependencies = ctor.GetParameters()
                               .Select(t => t.ParameterType);

            foreach (var dependency in dependencies)
            {
                var isRegistred = factory.Registrations
                                  .Any(t => t.Binding == dependency);

                if (!isRegistred)
                {
                    errors.Add($"Missing dependency `{dependency.GetRightFullName()}` "
                               + $"for implementation `{direct.Implementation.GetRightFullName()}` "
                               + $"and resolving type `{direct.Binding.GetRightFullName()}`");
                }
            }
        }
Esempio n. 30
0
        private void OnExecute(XmlElement viewInfo)
        {
            if (viewInfo == null)
            {
                throw new ArgumentNullException("viewInfo");
            }

            var atributes = viewInfo.Attributes;

            var module    = atributes.GetNamedItem("Module");
            var presenter = atributes.GetNamedItem("Presenter");
            var title     = atributes.GetNamedItem("Title");

            if (module == null)
            {
                throw new ArgumentException("Atributo 'module' não encontrado!");
            }

            if (presenter == null)
            {
                throw new ArgumentException("Atributo 'presenter' não encontrado!");
            }

            if (title == null)
            {
                throw new ArgumentException("Atributo 'title' não encontrado!");
            }

            _moduleManager.LoadModule(module.Value);
            ContainerRegistration reg = _container.Registrations.Single <ContainerRegistration>(g => g.Name == presenter.Value);

            if (reg == null)
            {
                throw new ArgumentException(String.Format("Formulário identificado por '{0}' não encontrado!", presenter.Value));
            }

            _breadCrumb.AddCrumb(title.Value, (_container.Resolve(reg.RegisteredType, presenter.Value) as ICrumbViewContent));
        }
 public ConfigureServiceLayer(ContainerRegistration container_services)
 {
     this.container_services = container_services;
 }
 public ConfigureApplicationCommands(ContainerRegistration container_services)
 {
     this.container_services = container_services;
 }
 public ConfigureCoreComponents(ContainerRegistration registration_services)
 {
     this.registration_services = registration_services;
 }
 public ConfigureFrontController(ContainerRegistration container_services)
 {
     this.container_services = container_services;
 }
 public DefaultStartupCommandFactory(ContainerRegistration registration)
 {
     this.registration = registration;
 }