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; }
public void Apply(Component component, ComponentRegistration registration) { AbstractConfigurationRunner.Kernel.Register( Castle.MicroKernel.Registration.Component.For(interceptorType).OnlyNewServices() ); registration.Interceptors(InterceptorReference.ForType(interceptorType)).First .OverWrite(); }
public override void Apply(Component component, ComponentRegistration registration) { if (factoryMethod == null) { base.Apply(component, registration); } else { registration.UsingFactoryMethod(factoryMethod); } }
void IComponentExtension.Apply(Component component, ComponentRegistration registration) { if (!string.IsNullOrEmpty(startMethod)) { registration.StartUsingMethod(startMethod); } if (!string.IsNullOrEmpty(stopMethod)) { registration.StopUsingMethod(stopMethod); } }
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); }
// 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>(); }
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 }); } }
/// <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); }
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); }
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)); }
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)); }
/// <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); }
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); } }
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()); }
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; } } }
/// <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); }
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}"); } }
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)); }
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); }
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)); } }
/// <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); }
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()); } }
/// <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)); } }
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); }
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); }
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); }
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); } }
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; } }
/// <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); }
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); } }
/// <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)); } }
/// <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); }
// 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> >(); }
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); }
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(); }
/// <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); }
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"); }
private string BuildName(ComponentRegistration registration) { return registration.Implementation.Name; }
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; }
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); } }
private static ComponentRegistration<object> ApplyResolver(ComponentRegistration<object> registration, DynamicResolver resolver) { return registration.UsingFactoryMethod(resolver.FactoryFunc); }
private static ComponentRegistration<object> ApplyResolver(ComponentRegistration<object> registration, StaticResolver resolver) { return registration.ImplementedBy(resolver.Target); }
public static void AddDependency(ComponentRegistration cr) { }
/// <summary> /// Returns the transient lifestyle for the controllers. /// </summary> /// <returns></returns> private void ConfigureControllers(ComponentRegistration componentRegistration) { componentRegistration.LifeStyle.Transient.Configuration(); }
public override void Apply(Component component, ComponentRegistration registration) { registration.LifeStyle.PooledWithSize(initialPoolSize.GetValueOrDefault(), maxPoolSize.GetValueOrDefault()); }
public override void Apply(Component component, ComponentRegistration registration) { registration.LifeStyle.Custom(customLifestyleType); }
public DefaultInstaller(params ComponentRegistration<object>[] overrides) { _overrides = overrides; }
public virtual void Apply(Component component, ComponentRegistration registration) { registration.LifeStyle.Is(lifestyle); }
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); }
protected virtual void ConfigureConsumer(ComponentRegistration registration) { registration.Named(registration.Implementation.Name); }
private ComponentRegistration<ILendingLibraryDbContext> ConfigureLifestylePerRequest(ComponentRegistration<ILendingLibraryDbContext> componentRegistration) { return componentRegistration.LifestylePerWebRequest(); }
private static ComponentRegistration<object> ApplyResolver(ComponentRegistration<object> registration, InstanceResolver resolver) { return registration.Instance(resolver.Instance); }
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(); }
private object ConfigureRegistration(ComponentRegistration registration) { string typeName = GetTypeName(registration.Implementation); registration.Named(typeName); return registration; }
public virtual void Apply(Component component, ComponentRegistration registration) { registration.OnCreate(onCreate); }
public virtual void Apply(Component component, ComponentRegistration registration) { registration.AddDescriptor(this); }
private void Configurer(ComponentRegistration componentRegistration) { componentRegistration.LifeStyle.Is(LifestyleType.Transient).Named(componentRegistration.Implementation.Name); }
void IComponentExtension.Apply(Component component, ComponentRegistration registration) { ApplyConfiguration(component.Configuration); }
private static void ConfigureComponent(ComponentRegistration componentRegistration) { componentRegistration.Named(componentRegistration.Implementation.FullName); }