コード例 #1
0
        private static ComponentRegistration<object> ApplyName(ComponentRegistration<object> registration, string name)
        {
            if (string.IsNullOrEmpty(name))
                return registration;

            return registration.Named(name);
        }
        IEnumerable<Type> GetServices( ComponentRegistration r ) 
        {
            var bf = System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public;
            var property = r.GetType().GetProperties( bf ).Single( p => p.Name == "Services" );
            var types = property.GetValue( r, null ) as IEnumerable<Type>;

            return types;
        }
コード例 #3
0
        public void Apply(Component component, ComponentRegistration registration)
        {
            AbstractConfigurationRunner.Kernel.Register(
                Castle.MicroKernel.Registration.Component.For(interceptorType).OnlyNewServices()
                );

            registration.Interceptors(InterceptorReference.ForType(interceptorType)).First
                .OverWrite();
        }
コード例 #4
0
 public override void Apply(Component component, ComponentRegistration registration)
 {
     if (factoryMethod == null)
     {
         base.Apply(component, registration);
     }
     else
     {
         registration.UsingFactoryMethod(factoryMethod);
     }
 }
コード例 #5
0
        void IComponentExtension.Apply(Component component, ComponentRegistration registration)
        {
            if (!string.IsNullOrEmpty(startMethod))
            {
                registration.StartUsingMethod(startMethod);
            }

            if (!string.IsNullOrEmpty(stopMethod))
            {
                registration.StopUsingMethod(stopMethod);
            }
        }
コード例 #6
0
        public WindsorDependencyVisitor(Type serviceType, ObjectDef objectDef, bool isDependency)
        {
            _objectDef = objectDef;
            _registration = map(serviceType, objectDef, false);

            // NOTE[MT]: if class is registered as dependency
            // it should be registered as default service to pass
            // auto_wiring_applies_even_when_another_dependency_is_set_explicitly test
            if (isDependency && serviceType.IsClass)
                _components.Add(map(serviceType, objectDef, true));

            _registration = map(serviceType, objectDef, false);
            _components.Add(_registration);
        }
コード例 #7
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers().AddNewtonsoftJson();

            // Create the credential provider to be used with the Bot Framework Adapter.
            services.AddSingleton <ICredentialProvider, ConfigurationCredentialProvider>();

            // Register AuthConfiguration to enable custom claim validation.
            services.AddSingleton <AuthenticationConfiguration>();

            // register components.
            ComponentRegistration.Add(new DialogsComponentRegistration());
            ComponentRegistration.Add(new DeclarativeComponentRegistration());
            ComponentRegistration.Add(new AdaptiveComponentRegistration());
            ComponentRegistration.Add(new LanguageGenerationComponentRegistration());
            ComponentRegistration.Add(new QnAMakerComponentRegistration());
            ComponentRegistration.Add(new LuisComponentRegistration());

            // Create the Bot Framework Adapter with error handling enabled.
            // Note: some classes use the base BotAdapter so we add an extra registration that pulls the same instance.
            services.AddSingleton <IBotFrameworkHttpAdapter, TestBotHttpAdapter>();
            services.AddSingleton <BotAdapter>(sp => (BotFrameworkHttpAdapter)sp.GetService <IBotFrameworkHttpAdapter>());

            // Create the storage we'll be using for User and Conversation state. (Memory is great for testing purposes.)
            services.AddSingleton <IStorage, MemoryStorage>();

            // Create the User state. (Used in this bot's Dialog implementation.)
            services.AddSingleton <UserState>();

            // Create the Conversation state. (Used by the Dialog system itself.)
            services.AddSingleton <ConversationState>();

            // Register the skills client and skills request handler.
            services.AddSingleton <SkillConversationIdFactoryBase, SkillConversationIdFactory>();
            services.AddHttpClient <BotFrameworkClient, SkillHttpClient>();
            services.AddSingleton <ChannelServiceHandler, SkillHandler>();

            var resourceExplorer = new ResourceExplorer().AddFolder(this.Configuration.GetValue <string>("BotRoot"));

            services.AddSingleton(resourceExplorer);

            // Pass configuration to bot
            services.AddSingleton(this.Configuration);

            // Create the bot  In this case the ASP Controller is expecting an IBot.
            services.AddSingleton <IBot, TestBot>();
        }
コード例 #8
0
        public IEnumerable <IComponentRegistration> RegistrationsFor(Service service, Func <Service, IEnumerable <IComponentRegistration> > registrationAccessor)
        {
            if (!(service is IServiceWithType swt))
            {
                return(Enumerable.Empty <IComponentRegistration>());
            }

            var reg = _registrations.FirstOrDefault(x => x.Type == swt.ServiceType);

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

            var activatorRegistration = reg as IActivatorContainerRegistration;

            if (activatorRegistration != null)
            {
                var registration = new ComponentRegistration(
                    Guid.NewGuid(),
                    new DelegateActivator(swt.ServiceType, (c, p) =>
                {
                    var result = activatorRegistration.Activator(_resolver.WithContext(c));
                    return(result);
                }),
                    reg.Lifetime == Lifetime.Request ? PerRequestLifetime() : reg.Lifetime == Lifetime.Singleton ? (IComponentLifetime) new RootScopeLifetime() : new CurrentScopeLifetime(),
                    reg.Lifetime == Lifetime.Request || reg.Lifetime == Lifetime.Singleton ? InstanceSharing.Shared : InstanceSharing.None,
                    reg.Lifetime == Lifetime.ExternallyOwned ? InstanceOwnership.ExternallyOwned : InstanceOwnership.OwnedByLifetimeScope,
                    new[] { service },
                    new Dictionary <string, object>());
                return(new IComponentRegistration[] { registration });
            }
            else
            {
                var activatorData = new ConcreteReflectionActivatorData(reg.Type);
                var registration  = new ComponentRegistration(
                    Guid.NewGuid(),
                    activatorData.Activator,
                    reg.Lifetime == Lifetime.Request ? PerRequestLifetime() : reg.Lifetime == Lifetime.Singleton ? (IComponentLifetime) new RootScopeLifetime() : new CurrentScopeLifetime(),
                    reg.Lifetime == Lifetime.Request || reg.Lifetime == Lifetime.Singleton ? InstanceSharing.Shared : InstanceSharing.None,
                    reg.Lifetime == Lifetime.ExternallyOwned ? InstanceOwnership.ExternallyOwned : InstanceOwnership.OwnedByLifetimeScope,
                    new[] { service },
                    new Dictionary <string, object>());

                return(new IComponentRegistration[] { registration });
            }
        }
コード例 #9
0
        /// <summary>
        /// Create an Entity with the given fields
        /// </summary>
        /// <param name="dataType"></param>
        /// <param name="dataPoints"></param>
        /// <returns></returns>
        public static IEntity CreateEntity(string dataType, Dictionary <string, object> dataPoints)
        {
            var entity = ComponentRegistration.CreateInstance <IEntity>(dataType);

            if (entity != null)
            {
                var type = entity.GetType();
                foreach (var point in dataPoints)
                {
                    if (type.GetProperty(point.Key, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static) != null)
                    {
                        type.GetProperty(point.Key).SetValue(entity, point.Value);
                    }
                }
            }
            return(entity);
        }
コード例 #10
0
        private void RegisterComponent(Type interfaceType, string componentId, TypeName typeName,
                                       IPluginDescriptor plugin, IServiceDescriptor serviceDescriptor)
        {
            ComponentRegistration componentRegistration;

            if (IsAnEventHandler(interfaceType))
            {
                componentRegistration = RegisterEventHandlerProxy(interfaceType, plugin,
                                                                  serviceDescriptor, componentId);
            }
            else
            {
                componentRegistration = new ComponentRegistration(plugin, serviceDescriptor,
                                                                  componentId, typeName);
            }
            registry.RegisterComponent(componentRegistration);
        }
コード例 #11
0
        private static ComponentRegistration <TFactory> AttachConfiguration <TFactory>(
            ComponentRegistration <TFactory> componentRegistration,
            Action <TypedFactoryConfiguration> configuration,
            string defaultComponentSelectorKey)
            where TFactory : class
        {
            var selectorReference = GetSelectorReference(configuration, defaultComponentSelectorKey, typeof(TFactory));

            return(componentRegistration
                   .AddDescriptor(new ReferenceDependencyDescriptor(selectorReference))
                   .DynamicParameters((k, context, args) => {
                var selector = selectorReference.Resolve(k, context);
                args.AddTyped(selector);
                return k2 => k2.ReleaseComponent(selector);
            })
                   .AddAttributeDescriptor(TypedFactoryFacility.IsFactoryKey, bool.TrueString));
        }
コード例 #12
0
        public void Complete()
        {
            if (!NewInstanceActivated)
            {
                return;
            }

            var beginningHandler = CompletionBeginning;

            beginningHandler?.Invoke(this, new InstanceLookupCompletionBeginningEventArgs(this));

            ComponentRegistration.RaiseActivated(this, Parameters, _newInstance);

            var endingHandler = CompletionEnding;

            endingHandler?.Invoke(this, new InstanceLookupCompletionEndingEventArgs(this));
        }
コード例 #13
0
        /// <summary>
        /// Create an array of collectors
        /// </summary>
        /// <param name="collectorConfigs">An array of collector configurations</param>
        /// <returns>a list of collectors</returns>
        public static List <ICollector> CreateCollectors(CollectorConfiguration[] collectorConfigs)
        {
            var result = new List <ICollector>();

            foreach (var config in collectorConfigs)
            {
                ComponentRegistration.RegisterComponents(config);
            }
            ComponentRegistration.Build();
            foreach (var config in collectorConfigs)
            {
                var collector = ComponentRegistration.CreateInstance <ICollector>(config.Type);
                collector.Configure(config);
                result.Add(collector);
            }
            return(result);
        }
コード例 #14
0
        public static ComponentRegistration <T> ToWindsorLifeTime <T>(this ComponentRegistration <T> container, LifeTime lifeTime) where T : class
        {
            switch (lifeTime)
            {
            case LifeTime.Singleton:
                return(container.LifeStyle.Singleton);

            case LifeTime.PerWebRequest:
                return(container.LifeStyle.PerWebRequest);

            case LifeTime.PerThread:
                return(container.LifeStyle.PerThread);

            default:
                return(container.LifeStyle.Transient);
            }
        }
コード例 #15
0
        public static IRegistration FromOpenGenericServiceDescriptor(Microsoft.Extensions.DependencyInjection.ServiceDescriptor service)
        {
            ComponentRegistration <object> registration = Component.For(service.ServiceType)
                                                          .NamedAutomatically(UniqueComponentName(service));

            if (service.ImplementationType != null)
            {
                registration = UsingImplementation(registration, service);
            }
            else
            {
                throw new System.ArgumentException("Unsupported ServiceDescriptor");
            }

            return(ResolveLifestyle(registration, service)
                   .IsDefault());
        }
コード例 #16
0
        private void RegisterWindsor(Microsoft.Extensions.DependencyInjection.ServiceDescriptor item)
        {
            try
            {
                ComponentRegistration <object> r = null;
                if (item.ImplementationType != null)
                {
                    if (_container.Kernel.HasComponent(item.ImplementationType))
                    {
                        return;
                    }
                    r = Component.For(item.ServiceType).ImplementedBy(item.ImplementationType);
                }
                else if (item.ImplementationFactory != null)
                {
                    var provider = WindsorRegistrationHelper.CreateServiceProvider(_container, this);
                    r = Component.For(item.ServiceType).UsingFactoryMethod(() => item.ImplementationFactory.Invoke(provider));
                }
                else if (item.ImplementationInstance != null)
                {
                    r = Component.For(item.ServiceType).UsingFactoryMethod(() => item.ImplementationInstance);
                }

                if (item.Lifetime == ServiceLifetime.Scoped)
                {
                    _container.Register(r.LifestyleScoped());
                }
                else if (item.Lifetime == ServiceLifetime.Transient)
                {
                    _container.Register(r.LifestyleTransient());
                }
                else if (item.Lifetime == ServiceLifetime.Singleton)
                {
                    _container.Register(r.LifestyleSingleton());
                }
            }
            catch (Exception ex)
            {
                if (!ex.Message.Contains("Component Microsoft.Extensions.Options.OptionsManager`1 could not be registered") &&
                    !ex.Message.Contains("Component Late bound Microsoft.Extensions.Options.IConfigureOptions`1[[Microsoft.Extensions.Logging.LoggerFilterOptions, Microsoft.Extensions.Logging"))
                {
                    // Known issue at: https://gist.github.com/cwe1ss/050a531e2711f5b62ab0
                    throw;
                }
            }
        }
コード例 #17
0
        /// <summary>
        /// Names a component registration for an <see cref="IDatabaseConnectionStringProvider"/> using
        /// the supplied enumeration value's name as the suffix on the key.
        /// </summary>
        /// <typeparam name="T">The service type being registered.</typeparam>
        /// <typeparam name="TEnum">The type of the <see cref="Enum"/> whose values represent the databases used by the application.</typeparam>
        /// <param name="registration">The <see cref="ComponentRegistration"/> instance.</param>
        /// <param name="database">The enumeration value representing the database to use for naming the registration.</param>
        /// <returns>The <see cref="ComponentRegistration"/> instance, for method chaining.</returns>
        public static ComponentRegistration <T> NamedForDatabase <T, TEnum>(this ComponentRegistration <T> registration, TEnum database)
            where T : class, IDatabaseConnectionStringProvider
        {
            // Only enumerations are supported
            if (!typeof(TEnum).IsEnum)
            {
                throw new ArgumentException("Generic type 'TEnum' must be an enumeration.");
            }

            string enumName = Enum.GetName(typeof(TEnum), database);

            string componentName = typeof(T).GetServiceNameWithSuffix(enumName);

            registration.Named(componentName);

            return(registration);
        }
コード例 #18
0
        private static ComponentRegistration <TService> ResolveLifestyle <TService>(ComponentRegistration <TService> registration, Microsoft.Extensions.DependencyInjection.ServiceDescriptor service) where TService : class
        {
            switch (service.Lifetime)
            {
            case ServiceLifetime.Singleton:
                return(registration.LifeStyle.NetStatic());

            case ServiceLifetime.Scoped:
                return(registration.LifeStyle.ScopedToNetServiceScope());

            case ServiceLifetime.Transient:
                return(registration.LifestyleNetTransient());

            default:
                throw new System.ArgumentException($"Invalid lifetime {service.Lifetime}");
            }
        }
コード例 #19
0
        private static ComponentRegistration <TFactoryInterface> RegisterInterfaceBasedFactory <TFactoryInterface>(
            ComponentRegistration <TFactoryInterface> registration, Action <TypedFactoryConfiguration> configuration)
            where TFactoryInterface : class
        {
            foreach (var serviceType in registration.Services)
            {
                Debug.Assert(serviceType.IsInterface, "serviceType.IsInterface");
                if (HasOutArguments(serviceType))
                {
                    throw new ComponentRegistrationException(
                              string.Format("Type {0} can not be used as typed factory because it has methods with 'out' arguments.", serviceType));
                }
            }
            var componentRegistration = AttachFactoryInterceptor(registration);

            return(AttachConfiguration(componentRegistration, configuration, TypedFactoryFacility.DefaultInterfaceSelectorKey));
        }
コード例 #20
0
ファイル: InstanceLookup.cs プロジェクト: marui888/Autofac
        public object Execute()
        {
            if (_executed)
            {
                throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, ComponentActivationResources.ActivationAlreadyExecuted, this.ComponentRegistration));
            }

            _executed = true;

            object?decoratorTarget = null;

            var sharing = _decoratorTargetComponent != null
                ? _decoratorTargetComponent.Sharing
                : ComponentRegistration.Sharing;

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

            if (!_activationScope.TryGetSharedInstance(ComponentRegistration.Id, out _newInstance))
            {
                _newInstance = sharing == InstanceSharing.Shared
                    ? _activationScope.CreateSharedInstance(ComponentRegistration.Id, () => CreateInstance(Parameters))
                    : CreateInstance(Parameters);
            }

            decoratorTarget = _newInstance;

            _newInstance = InstanceDecorator.TryDecorateRegistration(
                _service,
                ComponentRegistration,
                _newInstance,
                _activationScope,
                resolveParameters);

            if (_newInstance != decoratorTarget)
            {
                ComponentRegistration.RaiseActivating(this, resolveParameters, ref _newInstance);
            }

            var handler = InstanceLookupEnding;

            handler?.Invoke(this, new InstanceLookupEndingEventArgs(this, NewInstanceActivated));

            StartStartableComponent(decoratorTarget);

            return(_newInstance);
        }
コード例 #21
0
ファイル: WindsorExtensions.cs プロジェクト: csuffyy/BeeHive
        public static void DependsOnNamedAction(ComponentRegistration registration)
        {
            var implementationType = registration.Implementation;
            var constructor = implementationType.GetConstructors()
                .OrderByDescending(x=>x.GetParameters().Count()).FirstOrDefault();

            if(constructor==null)
                return;
            
            foreach (var parameterInfo in constructor.GetParameters())
            {
                var attribute = parameterInfo.GetCustomAttribute<DependsOnNamedAttribute>();
                if (attribute != null)
                    registration.DependsOn(Dependency.OnComponent(parameterInfo.ParameterType,
                        attribute.Name));
            }
        }
コード例 #22
0
        /// <summary>
        /// Create a mapper to use to transform data.
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public static IMapper CreateMapper(MapperConfiguration mapperConfig)
        {
            var mapper = ComponentRegistration.CreateInstance <IMapper>(mapperConfig.Type);

            if (mapper == null)
            {
                throw new NullReferenceException("Unable to create Collector.  Invalid Mapper defined.");
            }

            var converters = new Dictionary <string, IConverter>();

            if (mapperConfig.SourceTargetMappings != null && mapperConfig.SourceTargetMappings.Count > 0)
            {
                foreach (var converterConfig in mapperConfig.PipedConverters)
                {
                    var converter = ComponentRegistration.CreateInstance <IConverter>(converterConfig.Type);
                    if (converter == null)
                    {
                        throw new NullReferenceException("Unable to create Collector.  Invalid Converter defined.");
                    }

                    converter.Configure(converterConfig);
                    converters.Add(converter.Id, converter);
                }
            }
            else
            {
                foreach (var converterConfig in mapperConfig.Converters)
                {
                    var converter = ComponentRegistration.CreateInstance <IConverter>(converterConfig.Type);
                    if (converter == null)
                    {
                        throw new NullReferenceException("Unable to create Collector.  Invalid Converter defined.");
                    }

                    converter.Configure(converterConfig);
                    foreach (var key in converterConfig.LeftSideMap.Keys)
                    {
                        converters.Add(key, converter);
                    }
                }
            }
            mapper.Configure(mapperConfig, converters);
            return(mapper);
        }
コード例 #23
0
        public static ComponentRegistration <T> WithLifetime <T>(this ComponentRegistration <T> registration, Lifetime lifetime)
            where T : class
        {
            switch (lifetime)
            {
            case Lifetime.Transient:
                return(registration.LifestyleTransient());

            case Lifetime.Scope:
                return(registration.LifestyleScoped());

            case Lifetime.Singleton:
                return(registration.LifestyleSingleton());

            default:
                throw new NotSupportedException(lifetime.ToString());
            }
        }
コード例 #24
0
        /// <summary>
        /// Set the lifestyle of the registered builder
        /// </summary>
        private ComponentRegistration <T> ApplyLifestyle <T>(ComponentRegistration <T> registration, DependencyLifeStyle lifeStyle)
            where T : class
        {
            switch (lifeStyle)
            {
            case DependencyLifeStyle.Transient:
                return(registration.LifestyleTransient());

            case DependencyLifeStyle.Scoped:
                return(registration.LifestyleScoped());

            case DependencyLifeStyle.Singleton:
                return(registration.LifestyleSingleton());

            default:
                throw new ArgumentException(nameof(lifeStyle));
            }
        }
コード例 #25
0
        public void BuildCommandSwitchesToBuildMapView()
        {
            var objectSource  = new Mock <IContainerInfo>();
            var stringService = new ComponentRegistration();

            objectSource.Setup(o => o.GetServices()).Returns(
                new List <ComponentRegistration> {
                stringService,
            }
                );

            var visualizerViewModel = new VisualizerViewModel(objectSource.Object);

            visualizerViewModel.Components.MoveCurrentToFirst();
            visualizerViewModel.BuildCommand.Execute(stringService);

            Assert.AreEqual(View.BuildMap, visualizerViewModel.CurrentView);
        }
コード例 #26
0
        private static ComponentRegistration <object> RegisterComponents(this ComponentRegistration <object> builder, EDependencyLifecycle lifecycle)
        {
            switch (lifecycle)
            {
            case EDependencyLifecycle.Singleton:
                builder.LifestyleSingleton();
                break;

            case EDependencyLifecycle.Transient:
                builder.LifestyleTransient();
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(lifecycle), lifecycle, null);
            }

            return(builder);
        }
コード例 #27
0
        public static void Register <TInterface, TImplementation>(params KeyValuePair <string, object>[] parameters) where TInterface : class
            where TImplementation : TInterface
        {
            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }
            if (!parameters.Any())
            {
                throw new ArgumentException("Must pass at least one parameter");
            }

            ComponentRegistration <TInterface> componentRegistration = Component.For <TInterface>().ImplementedBy <TImplementation>();

            BuildComponentRegistrationWithParameters(ref componentRegistration, parameters);

            Resolver.Container.Register(componentRegistration.LifeStyle.Transient);
        }
コード例 #28
0
        ComponentRegistration <T> Lifestyle <T>(ComponentRegistration <T> registration, FeignClientLifetime lifetime)
            where T : class
        {
            switch (lifetime)
            {
            case FeignClientLifetime.Transient:
                return(registration.LifestyleTransient());

            case FeignClientLifetime.Singleton:
                return(registration.LifestyleSingleton());

            case FeignClientLifetime.Scoped:
                return(registration.LifestyleScoped());

            default:
                return(registration);
            }
        }
コード例 #29
0
        private void CreateFactory(ComponentRegistration key, Delegate factoryDelegate, InstanceMode instanceMode)
        {
            IFactoryProvider factoryProvider = null;

            if (instanceMode == InstanceMode.Transient)
            {
                factoryProvider = new TransientFactory(factoryDelegate);
            }

            if (instanceMode == InstanceMode.Singleton)
            {
                factoryProvider = new SingletonFactory(factoryDelegate);
            }

            lock (syncLock) {
                components[key] = factoryProvider;
            }
        }
コード例 #30
0
        /// <summary>
        /// Indicates that the specified component should be automatically implemented from
        /// the config.
        /// </summary>
        /// <typeparam name="T">The type of the interface to implement.</typeparam>
        /// <param name="registration">The registration.</param>
        /// <param name="configAction">Allows you to customize how the settings interface is implemented.</param>
        /// <returns>The registration.</returns>
        public static ComponentRegistration <T> FromAppConfig <T>(this ComponentRegistration <T> registration,
                                                                  Action <IConfigConfiguration <T> > configAction = null)
            where T : class
        {
            registration.Interceptors <AppConfigInterceptor>();

            if (configAction != null)
            {
                var configuration = new ConfigConfiguration <T>();
                configAction(configuration);

                registration.ExtendedProperties(new Property(AppConfigInterceptor.ComputedPropertiesKey,
                                                             configuration.ComputedDictionary));
                registration.ExtendedProperties(new Property(AppConfigInterceptor.PrefixKey, configuration.Prefix));
            }

            return(registration);
        }
コード例 #31
0
        private static ComponentRegistration <T> ApplyLifestyle <T>(ComponentRegistration <T> registration, DependencyLifeStyle lifeStyle)
            where T : class
        {
            switch (lifeStyle)
            {
            case DependencyLifeStyle.Transient:
                return(registration.LifestyleTransient());

            case DependencyLifeStyle.Singleton:
                return(registration.LifestyleSingleton());

            case DependencyLifeStyle.Scoped:
                return(registration.LifestyleScoped());

            default:
                return(registration);
            }
        }
コード例 #32
0
        /// <summary>
        /// Lifestyle conversion and application
        /// </summary>
        public static ComponentRegistration <T> ApplyLifestyle <T>(this ComponentRegistration <T> registration, DependencyLifeStyle lifeStyle)
            where T : class
        {
            switch (lifeStyle)
            {
            case DependencyLifeStyle.Transient:
                return(registration.LifestyleTransient());

            case DependencyLifeStyle.Scoped:
                return(registration.LifestyleScoped <LocalLifetimeScopeAccessor>());

            case DependencyLifeStyle.Singleton:
                return(registration.LifestyleSingleton());

            default:
                throw new ArgumentException(nameof(lifeStyle));
            }
        }
コード例 #33
0
        /// <summary>
        /// Initializes a new instance of the <see cref="DialogStateManager"/> class.
        /// </summary>
        /// <param name="dc">The dialog context for the current turn of the conversation.</param>
        /// <param name="configuration">Configuration for the dialog state manager. Default is <c>null</c>.</param>
        public DialogStateManager(DialogContext dc, DialogStateManagerConfiguration configuration = null)
        {
            ComponentRegistration.Add(new DialogsComponentRegistration());

            _dialogContext = dc ?? throw new ArgumentNullException(nameof(dc));
            Configuration  = configuration ?? dc.Context.TurnState.Get <DialogStateManagerConfiguration>();
            if (Configuration == null)
            {
                Configuration = new DialogStateManagerConfiguration();

                // Legacy memory scopes from static ComponentRegistration which is now obsolete.
                var memoryScopes = ComponentRegistration.Components
                                   .OfType <IComponentMemoryScopes>()
                                   .SelectMany(c => c.GetMemoryScopes())
                                   .ToList();

                // Merge new registrations from turn state
                memoryScopes.AddRange(dc.Context.TurnState.Get <IEnumerable <MemoryScope> >() ?? Enumerable.Empty <MemoryScope>());

                // Get all of the component memory scopes.
                foreach (var scope in memoryScopes)
                {
                    Configuration.MemoryScopes.Add(scope);
                }

                // Legacy memory scopes from static ComponentRegistration which is now obsolete.
                var pathResolvers = ComponentRegistration.Components
                                    .OfType <IComponentPathResolvers>()
                                    .SelectMany(c => c.GetPathResolvers())
                                    .ToList();

                // Merge new registrations from turn state
                pathResolvers.AddRange(dc.Context.TurnState.Get <IEnumerable <IPathResolver> >() ?? Enumerable.Empty <IPathResolver>());

                // Get all of the component path resolvers.
                foreach (var pathResolver in pathResolvers)
                {
                    Configuration.PathResolvers.Add(pathResolver);
                }
            }

            // cache for any other new dialogStatemanager instances in this turn.
            dc.Context.TurnState.Set(Configuration);
        }
コード例 #34
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();

            services.AddHttpClient().AddControllers().AddNewtonsoftJson();

            // Required for memory paths introduced by adaptive dialogs.
            ComponentRegistration.Add(new DialogsComponentRegistration());

            // Register declarative components
            ComponentRegistration.Add(new DeclarativeComponentRegistration());

            // Register adapive dialog components
            ComponentRegistration.Add(new AdaptiveComponentRegistration());

            // Add Language generation
            ComponentRegistration.Add(new LanguageGenerationComponentRegistration());

            // Add LUIS component
            ComponentRegistration.Add(new LuisComponentRegistration());

            // Create the Bot Framework Adapter with error handling enabled.
            services.AddSingleton <IBotFrameworkHttpAdapter, AdapterWithErrorHandler>();

            // Create the storage we'll be using for User and Conversation state. (Memory is great for testing purposes.)
            services.AddSingleton <IStorage, MemoryStorage>();

            // Create the User state. (Used in this bot's Dialog implementation.)
            services.AddSingleton <UserState>();

            // Create the Conversation state. (Used by the Dialog system itself.)
            services.AddSingleton <ConversationState>();

            // The Dialog that will be run by the bot.
            services.AddSingleton <RootDialog>();

            // Resource explorer to manage declarative resources for adaptive dialog
            var resourceExplorer = new ResourceExplorer().LoadProject(this.HostingEnvironment.ContentRootPath);

            services.AddSingleton(resourceExplorer);

            // Create the bot as a transient. In this case the ASP Controller is expecting an IBot.
            services.AddSingleton <IBot, DialogBot <RootDialog> >();
        }
コード例 #35
0
        private void Configure <TService>(ComponentRegistration <TService> conf, string name, bool isDefault, bool isFallback, Action <ComponentRegistration <TService> > configuration)
            where TService : class
        {
            if (isDefault)
            {
                conf.IsDefault();
            }
            if (isFallback)
            {
                conf.IsFallback();
            }

            if (!string.IsNullOrWhiteSpace(name))
            {
                conf.Named(name);
            }

            configuration?.Invoke(conf);
        }
コード例 #36
0
 public void Init()
 {
     ComponentRegistration.Reset();
     ComponentRegistration.RegisterComponent <IEntity>(TYPE_MOCKUSER);
     ComponentRegistration.RegisterComponent <IConverter>(TYPE_DATE_TIME_COMBINE_CONVERTER);
     ComponentRegistration.RegisterComponent <IConverter>(TYPE_DATE_TIME_UTC_CONVERTER);
     ComponentRegistration.RegisterComponent <IConverter>(TYPE_UPPER_CASE_CONVERTER);
     ComponentRegistration.RegisterTypesFromAssembly(new ThirdPartyAutofacConfiguration()
     {
         AssemblyName = ConfigurationTests.COLLECTOR_SDK_ASSEMBLY,
         Type         = "LoggerFacade"
     });
     ComponentRegistration.RegisterModulesFromAssembly(new ThirdPartyAutofacConfiguration()
     {
         AssemblyName = ConfigurationTests.NLOG_EXTRAS_ASSEMBLY,
         RegisterAll  = true
     });
     ComponentRegistration.Build();
 }
コード例 #37
0
        /// <summary>
        /// Create a Transformer.
        /// </summary>
        /// <param name="type">The name of the class to create.</param>
        /// <param name="id">The id of the transformer.</param>
        /// <param name="publishers">The publishers to use to publish the JSON data to a repository.</param>
        /// <param name="mappers">The mappers to use to transform/map the data.</param>
        /// <returns>A new handler.</returns>
        public static ITransformer CreateTransformer(TransformerConfiguration config, ITransformedDataHandler handler)
        {
            var mappers = new List <IMapper>();

            foreach (var mapperConfig in config.Mappers)
            {
                var mapper = CollectorFactory.CreateMapper(mapperConfig);
                if (mapper == null)
                {
                    throw new NullReferenceException("Unable to create Collector.  Invalid Mapper defined.");
                }

                mappers.Add(mapper);
            }
            var transformer = ComponentRegistration.CreateInstance <ITransformer>(config.Type);

            transformer.Configure(config, handler);
            return(transformer);
        }
コード例 #38
0
        private static ComponentRegistration<object> ApplyLifecycle(ComponentRegistration<object> registration, Lifecycle lifecycle)
        {
            if (lifecycle.Name == Lifecycle.Singleton.Name)
                return registration.LifeStyle.Singleton;

            if (lifecycle.Name == Lifecycle.Transient.Name)
                return registration.LifeStyle.Transient;

            if (lifecycle.Name == Lifecycle.PerWebRequest.Name)
                return registration.LifeStyle.PerWebRequest;

            if (lifecycle.Name == Lifecycle.Unmanaged.Name)
                return registration.LifeStyle.Custom<UnmanagedLifestyleManager>();

            if (lifecycle.Name == Lifecycle.Default.Name)
                return registration.LifeStyle.Singleton;

            if (lifecycle.Name == Lifecycle.ProviderDefault.Name)
                return registration;

            throw new ArgumentException(string.Format("Unknown Lifecycle : {0}", lifecycle), "lifecycle");
        }
コード例 #39
0
 private string BuildName(ComponentRegistration registration)
 {
     return registration.Implementation.Name;
 }
コード例 #40
0
ファイル: Component.cs プロジェクト: JackWangCUMT/rhino-tools
        public Component Register()
        {
            foreach (Type serviceType in _services)
            {
                if (_registration == null)
                {
                    _registration = new ComponentRegistration(serviceType);
                    _registration.Named(_name).ImplementedBy(_impl)
                        .DependsOn(_dependencies);

                    RegisterExtensions(_extensions);
                }
                else
                {
                    _registration.Forward(serviceType);
                }
            }

            if (_lifestyle.HasValue)
            {
                _registration.LifeStyle.Is(_lifestyle.Value);
            }

            kernel.Register(_registration);

            _dependencies.Clear();

            return this;
        }
コード例 #41
0
ファイル: CastleIoc.cs プロジェクト: kendarorg/Node.Cs.Old
		private static ComponentRegistration<object> InitializeLifeStyle(IComponent component, ComponentRegistration<object> componentFor)
		{
			switch (component.LifeStyle)
			{
				case (LifeStyle.Singleton):
					return componentFor.LifestyleSingleton();
				case (LifeStyle.Transient):
					return componentFor.LifestyleTransient();
				case (LifeStyle.WebRequest):
					return componentFor.LifestylePerWebRequest();
				case (LifeStyle.Pooled):
					return componentFor.LifestylePooled();
				default:
					throw new ContainerException("LifeStyle not allowed " + component.LifeStyle);
			}
		}
コード例 #42
0
 private static ComponentRegistration<object> ApplyResolver(ComponentRegistration<object> registration, DynamicResolver resolver)
 {
     return registration.UsingFactoryMethod(resolver.FactoryFunc);
 }
コード例 #43
0
 private static ComponentRegistration<object> ApplyResolver(ComponentRegistration<object> registration, StaticResolver resolver)
 {
     return registration.ImplementedBy(resolver.Target);
 }
コード例 #44
0
 public static void AddDependency(ComponentRegistration cr)
 {
     
 }
コード例 #45
0
 /// <summary>
 /// Returns the transient lifestyle for the controllers.
 /// </summary>
 /// <returns></returns>
 private void ConfigureControllers(ComponentRegistration componentRegistration)
 {
     componentRegistration.LifeStyle.Transient.Configuration();
 }
コード例 #46
0
 public override void Apply(Component component, ComponentRegistration registration)
 {
     registration.LifeStyle.PooledWithSize(initialPoolSize.GetValueOrDefault(), maxPoolSize.GetValueOrDefault());
 }
コード例 #47
0
 public override void Apply(Component component, ComponentRegistration registration)
 {
     registration.LifeStyle.Custom(customLifestyleType);
 }
コード例 #48
0
 public DefaultInstaller(params ComponentRegistration<object>[] overrides)
 {
     _overrides = overrides;
 }
コード例 #49
0
 public virtual void Apply(Component component, ComponentRegistration registration)
 {
     registration.LifeStyle.Is(lifestyle);
 }
コード例 #50
0
ファイル: CastleIoc.cs プロジェクト: kendarorg/Node.Cs.Old
		private ComponentRegistration<object> InitializeCreationPolicy(IComponent component, ComponentRegistration componentFor)
		{
			if (component.Instance != null)
			{
				return componentFor.Instance(component.Instance);
			}
			if (component.Implementation != null)
			{
				return componentFor.ImplementedBy(component.Implementation);
			}
			if (component.Factory != null)
			{
				return componentFor.UsingFactoryMethod(a => component.Factory(this));
			}
			throw new ContainerException("Implementation not allowed for interface " + component.Interface);
		}
コード例 #51
0
 protected virtual void ConfigureConsumer(ComponentRegistration registration)
 {
     registration.Named(registration.Implementation.Name);
 }
コード例 #52
0
 private ComponentRegistration<ILendingLibraryDbContext> ConfigureLifestylePerRequest(ComponentRegistration<ILendingLibraryDbContext> componentRegistration)
 {
     return componentRegistration.LifestylePerWebRequest();
 }
コード例 #53
0
 private static ComponentRegistration<object> ApplyResolver(ComponentRegistration<object> registration, InstanceResolver resolver)
 {
     return registration.Instance(resolver.Instance);
 }
コード例 #54
0
ファイル: Component.cs プロジェクト: oz-systems/rhino-commons
        public void Register()
        {
            _registration = new ComponentRegistration(_services.ToArray());
            _registration.Named(_name).ImplementedBy(_impl).DependsOn(_dependencies);

            RegisterExtensions(_extensions);

            if (_lifestyle.HasValue)
            {
                _registration.LifeStyle.Is(_lifestyle.Value);
            }

            kernel.Register(_registration);

            _dependencies.Clear();
        }
コード例 #55
0
 private object ConfigureRegistration(ComponentRegistration registration)
 {
     string typeName = GetTypeName(registration.Implementation);
     registration.Named(typeName);
     return registration;
 }
コード例 #56
0
 public virtual void Apply(Component component, ComponentRegistration registration)
 {
     registration.OnCreate(onCreate);
 }
コード例 #57
0
 public virtual void Apply(Component component, ComponentRegistration registration)
 {
     registration.AddDescriptor(this);
 }
コード例 #58
0
 private void Configurer(ComponentRegistration componentRegistration)
 {
     componentRegistration.LifeStyle.Is(LifestyleType.Transient).Named(componentRegistration.Implementation.Name);
 }
コード例 #59
0
 void IComponentExtension.Apply(Component component, ComponentRegistration registration)
 {
     ApplyConfiguration(component.Configuration);
 }
コード例 #60
0
 private static void ConfigureComponent(ComponentRegistration componentRegistration)
 {
     componentRegistration.Named(componentRegistration.Implementation.FullName);
 }