private static INotificationEndPoint CreateNotificationEndPoint(IKernel kernel) { var cloudMediaContext = kernel.Resolve<CloudMediaContext>(); var cloudQueueClient = kernel.Resolve<CloudQueueClient>(); try { // ReSharper disable once ReplaceWithSingleCallToFirstOrDefault INotificationEndPoint endpoint = cloudMediaContext.NotificationEndPoints .Where(ep => ep.Name == UploadConfig.NotificationQueueName) .FirstOrDefault(); if (endpoint != null) return endpoint; // Make sure the queue exists in Azure Storage var notificationQueue = cloudQueueClient.GetQueueReference(UploadConfig.NotificationQueueName); notificationQueue.CreateIfNotExists(); // Create the endpoint return cloudMediaContext.NotificationEndPoints.Create(UploadConfig.NotificationQueueName, NotificationEndPointType.AzureQueue, UploadConfig.NotificationQueueName); } finally { kernel.ReleaseComponent(cloudMediaContext); kernel.ReleaseComponent(cloudQueueClient); } }
public override object Resolve(IKernel kernel) { string key = null; var argument = arguments[0]; if (arguments.Length == 2) { key = (string)argument; argument = arguments[1]; } else if (argument is string) { return kernel.Resolve((string)argument, ComponentType); } if (argument is Uri) { argument = WcfEndpoint.At((Uri)argument); } var args = new HybridDictionary { { Guid.NewGuid().ToString(), argument } }; if (key == null) { return kernel.Resolve(ComponentType, args); } return kernel.Resolve(key, ComponentType, args); }
public static IFileProcessor Create(IKernel kernel, string typeKey) { var blobClient = kernel.Resolve<IBlobClient>(); var repositories = kernel.Resolve<IRepositoryContainer>(); if (typeKey == "ServiceOffering") { return new ServiceOfferingFileProcessor(blobClient, repositories); } else if (typeKey == "ServiceAttendance") { return new ServiceAttendanceFileProcessor(blobClient, repositories); } return null; }
/// <summary> /// Resolves the component(s) from given kernel. /// </summary> /// <param name = "kernel"></param> /// <returns>Resolved component(s).</returns> public virtual object Resolve(IKernel kernel) { if (string.IsNullOrEmpty(ComponentName) == false && kernel.HasComponent(ComponentName)) { if (ComponentType == null) { return kernel.Resolve(ComponentName, AdditionalArguments); } return kernel.Resolve(ComponentName, ComponentType, AdditionalArguments); } return kernel.Resolve(ComponentType, AdditionalArguments); }
private ICustomFieldManager Create(IKernel kernel, CreationContext context) { if (context.Handler.ComponentModel.Name == typeof(PublicController).FullName || context.Handler.ComponentModel.Name == typeof(DataFileController).FullName || context.Handler.ComponentModel.Name == typeof(CustomFieldController).FullName) { return kernel.Resolve<PublicFieldManager>(); } else if (context.Handler.ComponentModel.Name == typeof(PrivateHealthController).FullName) { return kernel.Resolve<PrivateHealthFieldManager>(); } throw new InvalidOperationException(string.Format("Cannot resolve {0} using given {1}.", typeof(ICustomFieldManager).Name, context.GetType().Name)); }
public IResponse Execute(IKernel kernel, IRequest request, RouteBase route) { // This is kind of nasty and needs to be smarter as well as handling bound models var controller = (SammyController)kernel.Resolve(route.Type); controller.Request = new Request(request); return (IResponse)route.Method.Invoke(controller, null); }
private static IMicrosoftStorageConfig GetAzureServiceConfig(IKernel k, ComponentModel cm, CreationContext cc) { var serviceConfig = new DefaultAzureServiceConfigurationProvider(k.Resolve<IAppConfigSettings>()).GetConfigRaw(); var webConfig = serviceConfig["Web"]; return new DictionaryAdapterFactory().GetAdapter<IMicrosoftStorageConfig>(webConfig); }
private void RegisterIMappingEngine(IKernel kernel) { kernel.Register( Component.For<IMappingEngine>() .UsingFactoryMethod(k => new MappingEngine(kernel.Resolve<IConfigurationProvider>())) ); }
private static ILogger CreateLogger(IKernel kernel, string name) { var logger = new Logger(); logger.Attach(kernel.Resolve <ILogListener>(name)); return(logger); }
/// <summary> /// 重写受保护的虚方法 /// </summary> /// <param name="requestContext"></param> /// <param name="controllerType"></param> /// <returns>成功解析Controller类型作为调用Kernel的Resolve的参数,返回即为需要被激活的Controller实例</returns> protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType) { if (controllerType == null) { throw new HttpException(404, string.Format("找不到路径为 '{0}' 的控制器", requestContext.HttpContext.Request.Path)); } return((IController)_kernel.Resolve(controllerType)); }
public object GetService(Type serviceType) { bool hasComponent = _kernel.HasComponent(serviceType); return(hasComponent ? _kernel.Resolve(serviceType) : _currentResolverScope.GetService(serviceType)); }
protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType) { if (controllerType == null) { return(null); } return((IController)kernel.Resolve(controllerType)); }
internal static ServiceHost CreateServiceHostInternal <M>(IKernel kernel, IWcfServiceModel serviceModel, ComponentModel model, params Uri[] baseAddresses) where M : IWcfServiceModel { var serviceHostBuilder = kernel.Resolve <IServiceHostBuilder <M> >(); return(serviceHostBuilder.Build(model, (M)serviceModel, baseAddresses)); }
/// <summary> /// This method is used internally /// </summary> private static ChannelCreator CreateChannelCreatorInternal <TModel>( IKernel kernel, IWcfClientModel clientModel, ComponentModel model, out IWcfBurden burden) where TModel : IWcfClientModel { var channelBuilder = kernel.Resolve <IChannelBuilder <TModel> >(); return(channelBuilder.GetChannelCreator((TModel)clientModel, model.GetServiceContract(), out burden)); }
private static CloudQueueClient CreateCloudQueueClient(IKernel kernel) { var storageAccount = kernel.Resolve<CloudStorageAccount>(); CloudQueueClient client = storageAccount.CreateCloudQueueClient(); kernel.ReleaseComponent(storageAccount); return client; }
public IList<IAspect> CreateAspects(IKernel kernel) { List<IAspect> result = new List<IAspect>(); foreach(String id in AspectComponents.Keys) { result.Add((IAspect) kernel.Resolve(id, typeof(IAspect ))); } return result; }
protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType) { if (controllerType == null) { throw new HttpException(404, string.Format("The controller for path '{0}' could not be found.", requestContext.HttpContext.Request.Path)); } return((IController)_kernel.Resolve(controllerType)); }
private void ConfigureCache(IKernel kernel, IEducationContext instance) { if (EnableCaching) { instance.Cache = kernel.Resolve<ICache>(); instance.CachingPolicy = CachingPolicy.CacheAll; } }
public override void ProcessModel(IKernel kernel, ComponentModel model) { if (model.Service is IBehaviorStore) { foreach (var node in kernel.GraphNodes.OfType<ComponentModel>()) { SetProxyInformation(node, kernel.Resolve<IBehaviorConfigurator>()); } return; } if (!kernel.HasComponent(typeof (IBehaviorStore))) return; var behaviorToProxyResolver = kernel.Resolve<IBehaviorConfigurator>(); //Get the proxy info SetProxyInformation(model, behaviorToProxyResolver); }
void IInterceptor.Intercept(IInvocation invocation) { Contract.Assume(_State == InterceptorState.Active || _State == InterceptorState.Initialized); Contract.Assume(invocation != null); var txManagerC = _Kernel.Resolve <TransactionManager>(); ITransactionManager txManager = txManagerC; var mTxMethod = _MetaInfo.Do(x => x.AsTransactional(invocation.Method.DeclaringType.IsInterface ? invocation.MethodInvocationTarget : invocation.Method)); var mTxData = mTxMethod.Do(x => txManager.CreateTransaction(x)); _State = InterceptorState.Active; try { if (!mTxData.HasValue) { if (mTxMethod.HasValue && mTxMethod.Value.Mode == TransactionScopeOption.Suppress) { _Logger.Info("supressing ambient transaction"); if (_Logger.IsInfoEnabled) { _Logger.Info("supressing ambient transaction"); } using (new TxScope(null, _Logger.CreateChildLogger("TxScope"))) invocation.Proceed(); } else { invocation.Proceed(); } return; } var transaction = mTxData.Value.Transaction; Contract.Assume(transaction.State == TransactionState.Active, "from post-condition of ITransactionManager CreateTransaction in the (HasValue -> ...)-case"); if (mTxData.Value.ShouldFork) { var task = ForkCase(invocation, mTxData.Value); txManagerC.EnlistDependentTask(task); } else { SynchronizedCase(invocation, transaction); } } finally { _Kernel.ReleaseComponent(txManagerC); } }
protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType) { if (controllerType == null) { throw new HttpException(404, string.Format("El controlador para la dirección '{0}' No pudo ser encontrado.", requestContext.HttpContext.Request.Path)); } return((IController)_kernel.Resolve(controllerType)); }
internal BackgroundServerContext(IKernel kernel) { if (kernel == null) { throw new ArgumentNullException(nameof(kernel)); } Console = kernel.Resolve <IConsoleWriter>(); }
protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType) { if (controllerType == null || !kernel.HasComponent(controllerType)) { return(base.GetControllerInstance(requestContext, controllerType)); } return((IController)kernel.Resolve(controllerType)); }
protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType) { if (controllerType == null) { //throw new HttpException(404, string.Format("当前对{0}的请求不存在", requestContext.HttpContext.Request.Path)); return(null); } return((IController)_ikernel.Resolve(controllerType)); }
protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType) { if (controllerType == null) { throw new HttpException(404, string.Format("These are not the controllers you are looking for: '{0}'", requestContext.HttpContext.Request.Path)); } return((IController)_kernel.Resolve(controllerType)); }
protected async Task <TSlot> AddSlotAsync() { TSlot slot = kernel.Resolve <TSlot>(); Slots.Add(slot); await Task.Yield(); return(slot); }
public object GetService(Type serviceType) { if (Kernel.HasComponent(serviceType)) { return(Kernel.Resolve(serviceType)); } return(DefaultMvcResolver.GetService(serviceType)); }
public ContainerContext(IKernel kernel) { this.kernel = kernel; EnsureContainerContextStoreRegistered(); contextStore = kernel.Resolve <IContainerContextStore>(); contextStore.RegisterCurrent(this); }
private static CloudQueueClient CreateCloudQueueClient(IKernel kernel) { var storageAccount = kernel.Resolve <CloudStorageAccount>(); CloudQueueClient client = storageAccount.CreateCloudQueueClient(); kernel.ReleaseComponent(storageAccount); return(client); }
protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType) { if (controllerType == null) { throw new ArgumentNullException(); } return((IController)_kernel.Resolve(controllerType)); }
protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType) { if (controllerType == null) { // Throw exception. Can't resolve null type. } return((IController)kernel.Resolve(controllerType)); }
private static LeaseManagerConfig CreateLeaseManagerConfig(IKernel kernel) { // Configure the lease manager var configRetriever = kernel.Resolve<IGetEnvironmentConfiguration>(); var leaseManagerConfig = new LeaseManagerConfig { LeaseName = "SampleDataJobs", UniqueId = configRetriever.UniqueInstanceId }; kernel.ReleaseComponent(configRetriever); return leaseManagerConfig; }
protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType) { if (controllerType == null) { string message = Resources.Error.ControllerNotFound.FormatWith(requestContext.HttpContext.Request.Path); throw new HttpNotFoundException(message); } return((IController)kernel.Resolve(controllerType)); // this also resolves the IActionInvoker. }
public ContainerContext(IKernel kernel) { this.kernel = kernel; EnsureContainerContextStoreRegistered(); contextStore = kernel.Resolve<IContainerContextStore>(); contextStore.RegisterCurrent(this); }
public object Resolve( CreationContext context, ISubDependencyResolver contextHandlerResolver, ComponentModel model, DependencyModel dependency) { return(queueProcessorNodeTypes.Select(type => kernel.Resolve(typeof(IQueueProcessorNode <>).MakeGenericType(type)))); }
public void Setup() { kernel = new DefaultKernel(); kernel.AddFacility<MethodValidatorFacility>(); kernel.Register(Component.For<IComplexService>().ImplementedBy<ComplexService>()); //Add the WindsorContainer so we have an IProxyFactory instance WindsorContainer container = new WindsorContainer(kernel, new DefaultComponentInstaller()); service = kernel.Resolve<IComplexService>(); }
private static CloudStorageAccount CreateCloudStorageAccount(IKernel kernel) { // Get Azure configurations var configRetriever = kernel.Resolve<IGetEnvironmentConfiguration>(); string storageConnectionString = configRetriever.GetSetting(StorageConnectionStringAppSettingsKey); kernel.ReleaseComponent(configRetriever); return CloudStorageAccount.Parse(storageConnectionString); }
public IController CreateController(RequestContext requestContext, string controllerName) { var controllerKey = controllerName.ToLowerInvariant() + "controller"; object area; if (requestContext.RouteData.Values.TryGetValue("area", out area)) { var areaControllerKey = Convert.ToString(area).ToLowerInvariant() + "." + controllerKey; if (_kernel.HasComponent(areaControllerKey)) { //requestContext.RouteData.Values["controller"] = area + "/" + controllerName; return(_kernel.Resolve <IController>(areaControllerKey)); } } return(_kernel.HasComponent(controllerKey) ? _kernel.Resolve <IController>(controllerKey) : null); }
public IHttpController Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType) { if (controllerType == null) { throw new HttpException(500, "Error, could not find api controller"); } return((IHttpController)_kernel.Resolve(controllerType)); }
private object ResolveDecorator(IKernel kernel, object instance, Type type) { Arguments arguments = new Arguments(); arguments.Add("decorated", instance); var result = kernel.Resolve(type, arguments); return(result); }
public void Dispatch(string[] args) { var commandArguments = args.TakeWhile(x => !x.StartsWith("-")).Take(2); var commandTypeNameCandidate = commandArguments.Any() ? string.Concat(commandArguments.Skip(1).FirstOrDefault(), args[0]) : "help"; Type matchingType; int argsToSkip = 0; if (_typeNameMatcher.IsSatisfiedBy(commandTypeNameCandidate)) { matchingType = _typeNameMatcher.GetMatchedType(commandTypeNameCandidate); argsToSkip = commandArguments.Count(); } else if (_aliasMatcher.IsSatisfiedBy(args[0])) { matchingType = _aliasMatcher.GetMatchedType(args[0]); argsToSkip = 1; } else { throw new DispatchException(string.Format("The command \"{0}\" doesn't match a command name or alias", string.Join(" ", args))); } var command = (Command)_kernel.Resolve(matchingType); try { command.Execute(args.Skip(argsToSkip).ToArray()); } catch (ApiException exception) { throw new DispatchException(string.Format("An error occured while connecting to the API. {0}", exception.Message)); } catch (CommandException exception) { command.WriteUsage(invokedWith: string.Join(" ", commandArguments), writer: _kernel.Resolve <TextWriter>()); if (!(exception is HelpException)) { throw new DispatchException(exception.Message); } } }
public void ProcessModel(IKernel kernel, ComponentModel model) { kernel.Resolve <IAbpModuleManager>().Modules.ForEach(m => { if (m.Instance is BlocksModule) { ((BlocksModule)m.Instance).OnRegistered(kernel, model); } }); }
public object Resolve( CreationContext context, ISubDependencyResolver contextHandlerResolver, ComponentModel model, DependencyModel dependency) { Type mock = typeof(Mock <>).MakeGenericType(dependency.TargetType); return(((Mock)kernel.Resolve(mock)).Object); }
public override void ProcessModel(IKernel kernel, ComponentModel model) { if (_MetaStore == null) _MetaStore = kernel.Resolve<ITransactionMetaInfoStore>(); Contract.Assume(model.Implementation != null); Validate(model); AddInterceptor(model); }
public object GetService(Type serviceType) { object service = _defaultResolver.GetService(serviceType); if (service == null && _kernel.HasComponent(serviceType)) { try { service = _kernel.Resolve(serviceType); } catch (Exception ex) { _kernel.Resolve <ILogger>().LogError(ex); throw; } } return(service); }
public IHttpController CreateController(HttpControllerContext controllerContext, string controllerName) { var controller = _kernel.Resolve <IHttpController>(String.Format("Web.Api.Controllers.{0}Controller", controllerName)); controllerContext.Controller = controller; controllerContext.ControllerDescriptor = new HttpControllerDescriptor(GlobalConfiguration.Configuration, controllerName, controller.GetType()); return(controllerContext.Controller); }
public static EducationDataContext Create(IKernel kernel) { lock (LockObject) { EducationDataContext instance = new EducationDataContext(); IDataContextConfigurator configurator = kernel.Resolve<IDataContextConfigurator>(); configurator.Configure(kernel, instance); return instance; } }
public bool TypeContainPointcut(Type type, IKernel kernel) { foreach (String id in PointcutComponents.Keys) { IPointcut pcuts = (IPointcut)kernel.Resolve( id, typeof(IPointcut)); if (pcuts.TypeContainPointcut(type)) return true; } return false; }
public bool IsPointcutMethod(System.Reflection.MethodInfo info, IKernel kernel) { foreach (String id in PointcutComponents.Keys) { IPointcut pcuts = (IPointcut) kernel.Resolve( id, typeof(IPointcut)); if (pcuts.IsPointcutMethod(info)) return true; } return false; }
private static CloudStorageAccount CreateCloudStorageAccount(IKernel kernel) { // Get Azure configurations var configRetriever = kernel.Resolve <IGetEnvironmentConfiguration>(); string storageConnectionString = configRetriever.GetSetting(StorageConnectionStringAppSettingsKey); kernel.ReleaseComponent(configRetriever); return(CloudStorageAccount.Parse(storageConnectionString)); }
internal Func<long, FactoryContext> ContextFactory(IKernel kernel) { var factory = new Func<long, FactoryContext>(executionId => { var context = kernel.Resolve<FactoryContext>(); context.ExecutionId = executionId; return context; }); return factory; }
/// <summary> /// Executes task. /// </summary> /// <param name="application">The application.</param><param name="kernel">The kernel.</param> public void Execute(IApplication application, IKernel kernel) { var configurationManager = kernel.Resolve<IConfigurationManager>(); var resourcesDirectory = configurationManager.AppSettings[ResourcesDirectoryKey]; if (String.IsNullOrEmpty(resourcesDirectory)) { resourcesDirectory = DefaultResourcesDirectory; } var resourceCacheHolder = new YamlResourceCacheHolder(application.Environment, Path.Combine(application.RootPath, resourcesDirectory)); kernel.Register(Component.For<IResourceCachesHolder>().Instance(resourceCacheHolder).LifeStyle.Singleton); }
public void ProcessModel(IKernel kernel, ComponentModel model) { if (model.ImplementationIsAListener() == false) { return; } var broker = kernel.Resolve<IEventRegister>(); model.Lifecycle.Add(new RegisterWithEventBroker(broker)); model.Lifecycle.Add(new UnregisterWithEventBroker(broker)); }
private static MediaServicesCredentials CreateCredentials(IKernel kernel) { // Get Azure configurations var configRetriever = kernel.Resolve<IGetEnvironmentConfiguration>(); string mediaServicesAccountName = configRetriever.GetSetting(MediaServicesNameAppSettingsKey); string mediaServicesAccountKey = configRetriever.GetSetting(MediaServicesKeyAppSettingsKey); kernel.ReleaseComponent(configRetriever); // Return the credentials return new MediaServicesCredentials(mediaServicesAccountName, mediaServicesAccountKey); }
private static ISession CreateSession(IKernel kernel) { var sessionFactory = kernel.Resolve<ISessionFactory>(); try { return sessionFactory.OpenSession(); } finally { kernel.ReleaseComponent(sessionFactory); } }
private static ISessionFactory CreateSessionFactory(IKernel kernel) { var validatorEngine = kernel.Resolve<ValidatorEngine>(); var nhConfig = new NHibernate.Cfg.Configuration().Configure() .SetProperty(NHibernate.Cfg.Environment.CurrentSessionContextClass, typeof(ConversationSessionContext).AssemblyQualifiedName) .AddAssembly(typeof(User).Assembly); Security.Configure<User>(nhConfig, SecurityTableStructure.Prefix); nhConfig.Initialize(validatorEngine); return nhConfig.BuildSessionFactory(); }
private static IMicrosoftStorageConfig GetAzureServiceConfig(IKernel k, ComponentModel cm, CreationContext cc) { var serviceConfig = new DefaultAzureServiceConfigurationProvider(k.Resolve<IAppConfigSettings>()).GetConfigRaw(); Dictionary<string, string> workerConfig = null; if (!serviceConfig.TryGetValue("Worker", out workerConfig)) { workerConfig = new Dictionary<string, string>(); } return new DictionaryAdapterFactory().GetAdapter<IMicrosoftStorageConfig>(workerConfig); }
public override object Resolve(IKernel kernel) { if (arguments.Length == 1) { var argument = arguments[0]; if (argument is string) { return kernel.Resolve((string)argument, ComponentType); } else if (argument is IWcfClientModel || argument is IWcfEndpoint) { return kernel.Resolve(ComponentType, new { argument }); } else if (argument is Uri) { var endpoint = WcfEndpoint.At((Uri)argument); return kernel.Resolve(ComponentType, new { endpoint }); } } return null; }
private static YouTubeService CreateYouTubeService(IKernel kernel) { var configRetriever = kernel.Resolve<IGetEnvironmentConfiguration>(); string apiKey = configRetriever.GetSetting(YouTubeApiKey); kernel.ReleaseComponent(configRetriever); // Create client for YouTube API var youTubeInit = new BaseClientService.Initializer { ApiKey = apiKey, ApplicationName = "KillrVideo.SampleData.Worker" }; return new YouTubeService(youTubeInit); }
private static ISession CreateCassandraSession(IKernel kernel) { // Get cluster IP/host and keyspace from .config file var configRetriever = kernel.Resolve<IGetEnvironmentConfiguration>(); string clusterLocation = configRetriever.GetSetting(ClusterLocationAppSettingsKey); kernel.ReleaseComponent(configRetriever); // Start a cluster builder for connecting to Cassandra Builder builder = Cluster.Builder(); // Allow multiple comma delimited locations to be specified in the configuration string[] locations = clusterLocation.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(l => l.Trim()).ToArray(); foreach (string location in locations) { string[] hostAndPort = location.Split(new[] { ':' }, StringSplitOptions.RemoveEmptyEntries); if (hostAndPort.Length == 1) { // Just an IP address or host name builder = builder.AddContactPoint(hostAndPort[0]); } else if (hostAndPort.Length == 2) { // IP Address plus host name var ipEndPoint = new IPEndPoint(IPAddress.Parse(hostAndPort[0]), int.Parse(hostAndPort[1])); builder = builder.AddContactPoint(ipEndPoint); } else { throw new InvalidOperationException(string.Format("Unable to parse Cassandra cluster location '{0}' from configuration.", location)); } } // Use the Cluster builder to create a cluster Cluster cluster = builder.Build(); // Use the cluster to connect a session to the appropriate keyspace ISession session; try { session = cluster.Connect(Keyspace); } catch (Exception e) { Logger.Error(string.Format("Exception while connecting to keyspace '{0}' using hosts '{1}'", Keyspace, clusterLocation), e); throw; } return session; }