public void ProcessModel(IKernel kernel, ComponentModel model) { if (model.Implementation.IsDefined(typeof (UsesAutomaticSessionCreationAttribute), true)) { model.Interceptors.Add(new InterceptorReference(typeof (AutomaticSessionInterceptor))); } }
private IEnumerable<LifestyleDependency> GetMismatch(LifestyleDependency parent, ComponentModel component, ComponentsMap model2Meta) { if (parent.Handler.ComponentModel == component) { yield break; } var pair = model2Meta[component]; var handler = pair.Handler; var item = new LifestyleDependency(pair, parent); if (item.Mismatched()) { yield return item; } else { foreach (ComponentModel dependent in handler.ComponentModel.Dependents) { foreach (var mismatch in GetMismatch(item, dependent, model2Meta)) { yield return mismatch; } } } }
public object Resolve(CreationContext context, ISubDependencyResolver parentResolver, ComponentModel model, DependencyModel dependency) { return _kernel.ResolveAll(dependency.TargetType.GetElementType(), null); }
protected virtual void CollectFromConfiguration(ComponentModel model) { if (model.Configuration == null) return; var interceptors = model.Configuration.Children["interceptors"]; if (interceptors == null) return; foreach (var interceptor in interceptors.Children) { var value = interceptor.Value; if (!ReferenceExpressionUtil.IsReference(value)) { throw new Exception( String.Format("The value for the interceptor must be a reference to a component (Currently {0})", value)); } var reference = new InterceptorReference(ReferenceExpressionUtil.ExtractComponentKey(value)); model.Interceptors.Add(reference); model.Dependencies.Add(CreateDependencyModel(reference)); } var options = ProxyUtil.ObtainProxyOptions(model, true); CollectSelector(interceptors, options); CollectHook(interceptors, options); }
void SetUndefinedLifeStyleToTransient(Castle.Core.ComponentModel model) { if (model.LifestyleType == LifestyleType.Undefined) { model.LifestyleType = LifestyleType.Transient; } }
private void Kernel_ComponentDestroyed(ComponentModel model, object instance) { if (instance is IListener) { _eventPublisher.RemoveListener((IListener) instance); } }
private void UpdateActivator(ComponentModel model) { if (model.CustomComponentActivator == null) { model.CustomComponentActivator = typeof(WcfBehaviorActivator); } }
private void Kernel_ComponentCreated(ComponentModel model, object instance) { if (instance is IListener) { _eventPublisher.AddListener((IListener) instance); } }
private void UpdateLifestyle(ComponentModel model) { // NOTE: I really don't like that. This goes against Principle of least astonishment // and IMO this behavior should not be like that. I _could_ accept doing it // if (model.LifestyleType == LifestyleType.Undefined) model.LifestyleType = LifestyleType.Transient; }
public InterceptorReference[] SelectInterceptors(ComponentModel model, InterceptorReference[] interceptors) { return new[] { new InterceptorReference(interceptorType), }; }
/// <summary> /// Returns true if the resolver is able to satisfy the specified dependency. /// </summary> /// <param name = "context">Creation context, which is a resolver itself</param> /// <param name = "contextHandlerResolver">Parent resolver</param> /// <param name = "model">Model of the component that is requesting the dependency</param> /// <param name = "dependency">The dependency model</param> /// <returns> /// <c>true</c> /// if the dependency can be satisfied</returns> public bool CanResolve(CreationContext context, ISubDependencyResolver contextHandlerResolver, ComponentModel model, DependencyModel dependency) { // 1 - check for the dependency on CreationContext, if present if (CanResolveFromContext(context, contextHandlerResolver, model, dependency)) { return true; } // 2 - check with the model's handler, if not the same as the parent resolver if (CanResolveFromHandler(context, contextHandlerResolver, model, dependency)) { return true; } // 3 - check within parent resolver, if present if (CanResolveFromContextHandlerResolver(context, contextHandlerResolver, model, dependency)) { return true; } // 4 - check within subresolvers if (CanResolveFromSubResolvers(context, contextHandlerResolver, model, dependency)) { return true; } // 5 - normal flow, checking against the kernel return CanResolveFromKernel(context, model, dependency); }
private void Kernel_ComponentModelCreated(ComponentModel model) { IEnumerable <Type> services = model.Services; bool isView = services.Any(x => x.GetInterface("IView") != null); // if (!services.Select(service => typeof (IView).IsAssignableFrom(service)).Any(isView => isView)) // { // return; // } // // if (model.CustomComponentActivator == null) // { // model.CustomComponentActivator = typeof (WpfWindowActivator); // } // bool isView = model // if ( !isView ) { return; } if ( model.CustomComponentActivator == null ) { model.CustomComponentActivator = typeof( WpfWindowActivator ); } }
private TransactionConfig CreateTransactionConfig(ComponentModel model) { TransactionConfig config = new TransactionConfig(); GatherTransactionAttributes(config, model.Implementation); GatherTransactionConfiguration(config, model); return config; }
public object Resolve(CreationContext context, ISubDependencyResolver contextHandlerResolver, ComponentModel model, DependencyModel dependency) { return contextHandlerResolver.Resolve(context, contextHandlerResolver, model, new DependencyModel(DependencyType.Service, typeof(IBookStore).FullName, typeof(IBookStore), false)); }
public NoResolvableConstructorFoundException(Type type, ComponentModel componentModel) : base( string.Format("Could not find resolvable constructor for {0}. Make sure all required dependencies are provided.", type.FullName), componentModel) { this.type = type; }
private IEnumerable<LifestyleDependency> GetMismatch(LifestyleDependency parent, ComponentModel component, Dictionary<ComponentModel, IHandler> model2Handler) { if (parent.Handler.ComponentModel == component) { yield break; } var handler = model2Handler[component]; var item = new LifestyleDependency(handler, parent); if (item.Mismatched()) { yield return item; } else { foreach (ComponentModel dependent in handler.ComponentModel.Dependents) { foreach (var mismatch in GetMismatch(item, dependent, model2Handler)) { yield return mismatch; } } } }
private void OnComponentModelCreated(ComponentModel model) { var isController = typeof(IController).IsAssignableFrom(model.Implementation); var isViewComponent = typeof(ViewComponent).IsAssignableFrom(model.Implementation); if (!isController && !isViewComponent) { return; } // Ensure it's transient model.LifestyleType = LifestyleType.Transient; model.InspectionBehavior = PropertiesInspectionBehavior.DeclaredOnly; if (isController) { var descriptor = ControllerInspectionUtil.Inspect(model.Implementation); controllerTree.AddController(descriptor.Area, descriptor.Name, model.Implementation); } if (isViewComponent) { componentRegistry.AddViewComponent(model.Name, model.Implementation); } }
protected static void SetOnBehalfAware(IOnBehalfAware onBehalfAware, ComponentModel target) { if (onBehalfAware != null) { onBehalfAware.SetInterceptedComponentModel(target); } }
public bool CanResolve(CreationContext context, ISubDependencyResolver contextHandlerResolver, ComponentModel model, DependencyModel dependency) { return dependency.TargetType != null && dependency.TargetType.IsArray && dependency.TargetType.GetElementType().IsInterface && !model.Parameters.Contains(dependency.DependencyKey); }
public void ProcessModel(IKernel kernel, ComponentModel model) { if (model.Configuration == null) { return; } var remoteserverAttValue = model.Configuration.Attributes["remoteserver"]; var remoteclientAttValue = model.Configuration.Attributes["remoteclient"]; var server = RemotingStrategy.None; var client = RemotingStrategy.None; if (remoteserverAttValue == null && remoteclientAttValue == null) { return; } if (remoteserverAttValue != null) { server = converter.PerformConversion<RemotingStrategy>(remoteserverAttValue); } if (remoteclientAttValue != null) { client = converter.PerformConversion<RemotingStrategy>(remoteclientAttValue); } DoSemanticCheck(server, model, client); ConfigureServerComponent(server, model.Implementation, model); ConfigureClientComponent(client, model.Services.Single(), model); }
/// <summary> /// Tries to configure the ComponentModel based on attributes. /// </summary> /// <param name="model">The model.</param> private void ConfigureBasedOnAttributes(ComponentModel model) { if (model.Implementation.IsDefined(typeof(TransactionalAttribute), true)) { metaStore.CreateMetaFromType(model.Implementation); } }
/// <summary> /// Constructs an AbstractComponentActivator /// </summary> protected AbstractComponentActivator(ComponentModel model, IKernel kernel, ComponentInstanceDelegate onCreation, ComponentInstanceDelegate onDestruction) { this.model = model; this.kernel = kernel; this.onCreation = onCreation; this.onDestruction = onDestruction; }
/// <summary> /// Searches for the component activator in the configuration and, if unsuccessful /// look for the component activator attribute in the implementation type. /// </summary> /// <param name = "kernel">The kernel instance</param> /// <param name = "model">The model instance</param> public virtual void ProcessModel(IKernel kernel, ComponentModel model) { if (!ReadComponentActivatorFromConfiguration(model)) { ReadComponentActivatorFromType(model); } }
public void ProcessModel(IKernel kernel, ComponentModel model) { if (model.Configuration == null) { return; } var mixins = model.Configuration.Children["mixins"]; if (mixins == null) { return; } var mixinReferences = new List<ComponentReference<object>>(); foreach (var mixin in mixins.Children) { var value = mixin.Value; var mixinComponent = ReferenceExpressionUtil.ExtractComponentKey(value); if (mixinComponent == null) { throw new Exception( String.Format("The value for the mixin must be a reference to a component (Currently {0})", value)); } mixinReferences.Add(new ComponentReference<object>("mixin-" + mixinComponent, mixinComponent)); } if (mixinReferences.Count == 0) { return; } var options = ProxyUtil.ObtainProxyOptions(model, true); mixinReferences.ForEach(options.AddMixinReference); }
protected void ConfigureServiceHost(ServiceHost serviceHost, IWcfServiceModel serviceModel, ComponentModel model) { serviceHost.Description.Behaviors.Add( new WindsorDependencyInjectionServiceBehavior(kernel, model) ); var burden = new WcfBurden(kernel); var contracts = new HashSet<ContractDescription>(); Dictionary<IWcfEndpoint, ServiceEndpoint> endpoints = null; if (serviceModel != null && serviceModel.Endpoints.Count > 0) { endpoints = new Dictionary<IWcfEndpoint, ServiceEndpoint>(); var builder = new ServiceEndpointBuilder(this, serviceHost); foreach (var endpoint in serviceModel.Endpoints) { endpoints.Add(endpoint, builder.AddServiceEndpoint(endpoint)); } } var extensions = new ServiceHostExtensions(serviceHost, kernel) .Install(burden, new WcfServiceExtensions()); if (serviceModel != null) { extensions.Install(serviceModel.Extensions, burden); } extensions.Install(burden, new WcfEndpointExtensions(WcfExtensionScope.Services)); if (endpoints != null) { foreach (var endpoint in endpoints) { var addContract = contracts.Add(endpoint.Value.Contract); new ServiceEndpointExtensions(endpoint.Value, addContract, kernel) .Install(endpoint.Key.Extensions, burden); } } if (serviceHost is IWcfServiceHost) { var wcfServiceHost = (IWcfServiceHost)serviceHost; wcfServiceHost.EndpointCreated += (_, e) => { var addContract = contracts.Add(e.Endpoint.Contract); var endpointExtensions = new ServiceEndpointExtensions(e.Endpoint, addContract, kernel) .Install(burden, new WcfEndpointExtensions(WcfExtensionScope.Services)); if (serviceModel != null) { endpointExtensions.Install(serviceModel.Extensions, burden); } }; } serviceHost.Extensions.Add(new WcfBurdenExtension<ServiceHostBase>(burden)); }
/// <summary> /// Queries the kernel's ConfigurationStore for a configuration /// associated with the component name. /// </summary> /// <param name="kernel"></param> /// <param name="model"></param> public virtual void ProcessModel(IKernel kernel, ComponentModel model) { IConfiguration config = kernel.ConfigurationStore.GetComponentConfiguration(model.Name) ?? kernel.ConfigurationStore.GetBootstrapComponentConfiguration(model.Name); model.Configuration = config; }
protected virtual void CollectFromConfiguration(ComponentModel model) { if (model.Configuration == null) return; IConfiguration interceptors = model.Configuration.Children["interceptors"]; if (interceptors == null) return; foreach(IConfiguration interceptor in interceptors.Children) { String value = interceptor.Value; if (!ReferenceExpressionUtil.IsReference(value)) { String message = String.Format( "The value for the interceptor must be a reference " + "to a component (Currently {0})", value); throw new ConfigurationErrorsException(message); } InterceptorReference interceptorRef = new InterceptorReference( ReferenceExpressionUtil.ExtractComponentKey(value) ); model.Interceptors.Add(interceptorRef); model.Dependencies.Add( CreateDependencyModel(interceptorRef) ); } }
public object Create(IProxyFactoryExtension customFactory, IKernel kernel, ComponentModel model, CreationContext context, params object[] constructorArguments) { throw new NotImplementedException( "You must supply an implementation of IProxyFactory " + "to use interceptors on the Microkernel"); }
/// <summary> /// Constructs a new ComponentModel by invoking /// the registered contributors. /// </summary> /// <param name = "name"></param> /// <param name = "services"></param> /// <param name = "classType"></param> /// <param name = "extendedProperties"></param> /// <returns></returns> public ComponentModel BuildModel(ComponentName name, Type[] services, Type classType, IDictionary extendedProperties) { var model = new ComponentModel(name, services, classType, extendedProperties); contributors.ForEach(c => c.ProcessModel(kernel, model)); return model; }
/// <summary> /// Reads the proxy behavior associated with the /// component configuration/type and applies it to the model. /// </summary> /// <exception cref="System.Exception"> /// If the conversion fails /// </exception> /// <param name="kernel"></param> /// <param name="model"></param> protected virtual void ReadProxyBehavior(IKernel kernel, ComponentModel model) { ComponentProxyBehaviorAttribute proxyBehaviorAtt = GetProxyBehaviorFromType(model.Implementation); if (proxyBehaviorAtt == null) { proxyBehaviorAtt = new ComponentProxyBehaviorAttribute(); } string useSingleInterfaceProxyAttrib = model.Configuration != null ? model.Configuration.Attributes["useSingleInterfaceProxy"] : null; #if !SILVERLIGHT string marshalByRefProxyAttrib = model.Configuration != null ? model.Configuration.Attributes["marshalByRefProxy"] : null; #endif var converter = kernel.GetConversionManager(); if (useSingleInterfaceProxyAttrib != null) { #pragma warning disable 0618 //call to obsolete method proxyBehaviorAtt.UseSingleInterfaceProxy = converter.PerformConversion<bool?>(useSingleInterfaceProxyAttrib).GetValueOrDefault(false); #pragma warning restore } #if !SILVERLIGHT if (marshalByRefProxyAttrib != null) { proxyBehaviorAtt.UseMarshalByRefProxy = converter.PerformConversion<bool?>(marshalByRefProxyAttrib).GetValueOrDefault(false); } #endif ApplyProxyBehavior(proxyBehaviorAtt, model); }
private void ProcessLateBoundModel(ComponentModel model) { var commission = new LateBoundConcerns(); if (model.Services.Any(s => s.Is<IInitializable>())) { model.Lifecycle.Add(InitializationConcern.Instance); } else { commission.AddConcern<IInitializable>(InitializationConcern.Instance); } if (model.Services.Any(s => s.Is<ISupportInitialize>())) { model.Lifecycle.Add(SupportInitializeConcern.Instance); } else { commission.AddConcern<ISupportInitialize>(SupportInitializeConcern.Instance); } if (commission.HasConcerns) { model.Lifecycle.Add(commission as ICommissionConcern); } if (model.Services.Any(s => s.Is<IDisposable>())) { model.Lifecycle.Add(DisposalConcern.Instance); } else { var decommission = new LateBoundConcerns(); decommission.AddConcern<IDisposable>(DisposalConcern.Instance); model.Lifecycle.Add(decommission as IDecommissionConcern); } }
public InterceptorReference[] SelectInterceptors(Castle.Core.ComponentModel model, Castle.Core.InterceptorReference[] interceptors) { var intercept = new List <InterceptorReference>(); String enableInstrumentation = ConfigurationManager.AppSettings["EnableInstrumentation"]; if (String.IsNullOrEmpty(enableInstrumentation) != true && Convert.ToBoolean(enableInstrumentation, CultureInfo.InvariantCulture)) { intercept.Add(InterceptorReference.ForType <LoggingInterceptor>()); } return(intercept.Concat(interceptors).ToArray()); }
void ComponentDestroyed(Castle.Core.ComponentModel model, object instance) { if (!(instance is IHandle)) { return; } if (_eventAggregator == null) { return; } _eventAggregator.Unsubscribe(instance); }
void ComponentCreated(Castle.Core.ComponentModel model, object instance) { if (!(instance is IHandle)) { return; } if (_eventAggregator == null) { _eventAggregator = Kernel.Resolve <IEventAggregator>(); } _eventAggregator.Subscribe(instance); }
public Boolean HasInterceptors(Castle.Core.ComponentModel model) { String[] interceptClasses = ConfigurationManager.AppSettings["InterceptClasses"].Split(';'); foreach (var interceptClass in interceptClasses) { if (!String.IsNullOrWhiteSpace(interceptClass)) { if (model.Name.EndsWith(interceptClass)) { return(true); } } } return(false); }
/// <inheritdoc /> public object Resolve(CreationContext context, ISubDependencyResolver contextHandlerResolver, Castle.Core.ComponentModel model, DependencyModel dependency) { Type genericArgument = null; if ((dependency.TargetType.IsGenericType) && (dependency.TargetType.GetGenericTypeDefinition() == typeof(IEnumerable <>))) { genericArgument = dependency.TargetType.GetGenericArguments()[0]; } else { dependency.TargetType.GetInterfaces().First(implemented => (implemented.IsGenericType) && (implemented.GetGenericTypeDefinition() == typeof(IEnumerable <>)) && ((genericArgument = implemented.GetGenericArguments()[0]) != null)); } var handlers = _kernel.GetAssignableHandlers(genericArgument).Distinct(HandlerEqualityComparer.Instance); var components = handlers .Where(h => h.CurrentState == HandlerState.Valid) .Select(h => h.Resolve(new CreationContext(genericArgument, context, true))) .ToArray(); var result = Array.CreateInstance(genericArgument, components.Length); components.CopyTo(result, 0); return(result); }
/// <summary>Initializes a new instance of the <see cref="NonPublicComponentActivator" /> class.</summary> /// <param name="model">Component model.</param> /// <param name="kernel">Castle Windsor kernel.</param> /// <param name="onCreation">Creation delegate.</param> /// <param name="onDestruction">Destruction delegate.</param> public NonPublicComponentActivator(Castle.Core.ComponentModel model, IKernelInternal kernel, ComponentInstanceDelegate onCreation, ComponentInstanceDelegate onDestruction) : base(model, kernel, onCreation, onDestruction) { }
/// <inheritdoc /> public bool CanResolve(CreationContext context, ISubDependencyResolver contextHandlerResolver, Castle.Core.ComponentModel model, DependencyModel dependency) { if (dependency.TargetType == null) { return(false); } Type genericArgument = null; if ((dependency.TargetType.IsGenericType) && (dependency.TargetType.GetGenericTypeDefinition() == typeof(IEnumerable <>))) { genericArgument = dependency.TargetType.GetGenericArguments()[0]; } else { dependency.TargetType.GetInterfaces().Any(implemented => (implemented.IsGenericType) && (implemented.GetGenericTypeDefinition() == typeof(IEnumerable <>)) && ((genericArgument = implemented.GetGenericArguments()[0]) != null)); } if ((genericArgument == null) || (!_kernel.HasComponent(genericArgument))) { return(false); } return(true); }