protected override void Configure(IKernel kernel, OrleansCodeConfig commonConfig) { kernel.Rebind <ServiceValidator>().To <MockServiceValidator>().InSingletonScope(); kernel.Rebind <IMetricsInitializer>().To <MetricsInitializerFake>(); kernel.Rebind <ILog>().ToConstant(new HttpLog(TraceEventType.Warning)); kernel.Rebind <IDependantClassFake>().To <DependantClassFake>().InSingletonScope(); }
public static void Bind() { Instance.Rebind <IPrintDocument>().To <WordTemplateDocument>(); Instance.Rebind <IPrintDocument>().To <ExcelTemplateDocument>(); Instance.Rebind <IPrintDocumentFactory>().To <PrintDocumentFactory>().InSingletonScope(); Instance.Rebind <ILogger>().ToConstant(LogManager.GetCurrentClassLogger()); }
protected override void Configure(IKernel kernel, BaseCommonConfig commonConfig) { Kernel = kernel; kernel.Rebind <ServiceValidator>().To <MockServiceValidator>().InSingletonScope(); kernel.Rebind <ICertificateLocator>().To <DummyCertificateLocator>().InSingletonScope(); kernel.Bind <ICalculatorService>().To <CalculatorService>().InSingletonScope(); }
public static void InjectRavenDbContext(IRavenDbContext ravenDbContext) { _ravenDbContext = ravenDbContext; NinjectKernel.Rebind <IRavenDbContext>().ToConstant(ravenDbContext); NinjectKernel.Rebind <IDb>().To <RavenDb>(); NinjectKernel.Rebind <IDocumentStore>().ToConstant(ravenDbContext.DocumentStore); }
private void SearchAssembliesAndRebindIConfig() { IAssemblyProvider aProvider = _kernel.Get <IAssemblyProvider>(); foreach (Type configType in aProvider.GetAllTypes().Where(ConfigObjectCreator.IsConfigObject)) { IConfigObjectCreator configObjectCreator = _kernel.Get <Func <Type, IConfigObjectCreator> >()(configType); if (!_kernel.IsBinded(typeof(Func <>).MakeGenericType(configType))) { dynamic getLatestLambda = configObjectCreator.GetLambdaOfGetLatest(configType); _kernel.Rebind(typeof(Func <>).MakeGenericType(configType)).ToMethod(t => getLatestLambda()); } Type sourceBlockType = typeof(ISourceBlock <>).MakeGenericType(configType); if (!_kernel.IsBinded(typeof(ISourceBlock <>).MakeGenericType(configType))) { _kernel.Rebind(sourceBlockType).ToMethod(t => configObjectCreator.ChangeNotifications); } if (!_kernel.IsBinded(typeof(Func <>).MakeGenericType(sourceBlockType))) { dynamic changeNotificationsLambda = configObjectCreator.GetLambdaOfChangeNotifications(sourceBlockType); _kernel.Rebind(typeof(Func <>).MakeGenericType(sourceBlockType)).ToMethod(t => changeNotificationsLambda()); } if (!_kernel.IsBinded(configType)) { _kernel.Rebind(configType).ToMethod(t => configObjectCreator.GetLatest()); } _configObjectsCache.RegisterConfigObjectCreator(configObjectCreator); } }
/// <summary> /// Load your modules or register your services here! /// </summary> /// <param name="kernel">The kernel.</param> private static void RegisterServices(IKernel kernel) { kernel.Bind(scanner => scanner.FromAssembliesMatching("Sfw.Sabp.Mca.*") .SelectAllClasses().NotInNamespaces(new[] { "Sfw.Sabp.Mca.Web.ViewModels.Validation" }) .BindAllInterfaces()); kernel.Bind <DbContext>().To <DataAccess.Ef.Mca>().InRequestScope(); kernel.Rebind <IUnitOfWork>().To <UnitOfWork>() .InRequestScope() .WithConstructorArgument(new DataAccess.Ef.Mca()); kernel.BindFilter <AuthorizeMcaUsersAttribute>(FilterScope.Global, 0); kernel.BindFilter <ErrorLoggerFilter>(FilterScope.Global, 0); kernel.BindFilter <AuditFilterAttribute>(FilterScope.Action, 0).WhenActionMethodHas <AuditAttribute>() .WithConstructorArgumentFromActionAttribute <AuditAttribute>("auditProperties", x => x.AuditProperties); kernel.BindFilter <AssessmentInProgressActionFilter>(FilterScope.Action, 0) .WhenActionMethodHas <AssessmentInProgressAttribute>() .WithConstructorArgumentFromActionAttribute <AssessmentInProgressAttribute>("actionParameterId", x => x.ActionParameterId); kernel.BindFilter <AssessmentCompleteActionFilter>(FilterScope.Action, 0) .WhenActionMethodHas <AssessmentCompleteAttribute>() .WithConstructorArgumentFromActionAttribute <AssessmentCompleteAttribute>("actionParameterId", x => x.ActionParameterId); kernel.BindFilter <AgreedToDisclaimerAuthorizeAttribute>(FilterScope.Controller, 0).WhenControllerHas <AgreedToDisclaimerAuthorizeAttributeNinject>(); kernel.BindFilter <AuthorizeAdministratorAttribute>(FilterScope.Action, 0).WhenActionMethodHas <AuthorizeAdministratorAttributeNinject>(); kernel.Rebind <ModelMetadataProvider>().To <CustomModelMetadataProvider>().InSingletonScope(); AssemblyScanner.FindValidatorsInAssembly(Assembly.GetExecutingAssembly()) .ForEach(match => kernel.Bind(match.InterfaceType).To(match.ValidatorType)); }
/// <summary> /// Load your modules or register your services here! /// </summary> /// <param name="kernel">The kernel.</param> private static void RegisterServices(IKernel kernel) { var assemblies = new[] { Assembly.GetExecutingAssembly(), Assembly.GetAssembly(typeof(IHostApplication)), // Rubberduck.VBEditor Assembly.GetAssembly(typeof(InspectionBase)), // Rubberduck.Inspections Assembly.GetAssembly(typeof(App)), // Rubberduck Assembly.GetAssembly(typeof(IIndenter)), // Rubberduck.SmartIndenter Assembly.GetAssembly(typeof(IParseCoordinator)) // Rubberduck.Parsing }; ApplyDefaultInterfacesConvention(kernel, assemblies); IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule("", out component).Object; kernel.Rebind <IVBE>().ToConstant(vbe).InRequestScope(); kernel.Rebind <IIndenter>().ToConstant(new Indenter(vbe, () => new IndenterSettings())).InRequestScope(); kernel.Bind <IDeclarationFinderFactory>().ToMethod(context => new DeclarationFinderFactory()); kernel.Rebind <IPersistanceService <CodeInspectionSettings> >().To <XmlPersistanceService <CodeInspectionSettings> >().InRequestScope(); kernel.Bind <IAssignedByValParameterQuickFixDialogFactory>().ToConstant(new Mock <IAssignedByValParameterQuickFixDialogFactory>().Object); kernel.Bind <RubberduckParserState>().ToSelf().InRequestScope(); kernel.Bind <IParseCoordinator>().To <ParseCoordinator>().InRequestScope(); BindCodeInspectionTypes(kernel); }
private void SetUpInitialData(InstallModel model, IDatabaseProvider provider) { NHibernateConfigurator configurator = new NHibernateConfigurator(provider); ISessionFactory sessionFactory = configurator.CreateSessionFactory(); ISession session = sessionFactory.OpenFilteredSession(CurrentRequestData.CurrentContext); IStatelessSession statelessSession = sessionFactory.OpenStatelessSession(); IKernel kernel = MrCMSApplication.Get <IKernel>(); kernel.Rebind <ISession>().ToMethod(context => session); kernel.Rebind <IStatelessSession>().ToMethod(context => statelessSession); Site site = new Site { Name = model.SiteName, BaseUrl = model.SiteUrl, CreatedOn = DateTime.UtcNow, UpdatedOn = DateTime.UtcNow }; using (ITransaction transaction = statelessSession.BeginTransaction()) { statelessSession.Insert(site); transaction.Commit(); } CurrentRequestData.CurrentSite = site; kernel.Get <IInitializeDatabase>().Initialize(model); kernel.Get <ICreateInitialUser>().Create(model); kernel.GetAll <IOnInstallation>() .OrderBy(installation => installation.Priority) .ForEach(installation => installation.Install(model)); }
/// <summary> /// Used to configure Kernel in abstract base-classes, which should apply to any concrete service that inherits from it. /// Should be overridden when creating a base-class that should include common behaviour for a family of services, without /// worrying about concrete service authors forgetting to call base.Configure(). Nevertheless, when overriding this method, /// you should always call base.PreConfigure(), and if all inheritors of the class are concrete services, you should also /// mark this method as sealed to prevent confusion with Configure(). /// </summary> /// <param name="kernel">Kernel that should contain bindings for the service.</param> protected virtual void PreConfigure(IKernel kernel) { kernel.Load <MicrodotModule>(); kernel.Load <MicrodotHostingModule>(); GetLoggingModule().Bind(kernel.Rebind <ILog>(), kernel.Rebind <IEventPublisher>()); kernel.Rebind <ServiceArguments>().ToConstant(Arguments); }
protected override void Configure(IKernel kernel, BaseCommonConfig commonConfig) { kernel.Rebind <IMetricsInitializer>().To <MetricsInitializerFake>().InSingletonScope(); kernel.Rebind <IDiscoverySourceLoader>().To <AlwaysLocalHost>().InSingletonScope(); action?.Invoke(kernel); kernel.Bind <ISlowService>().To <SlowService>().InSingletonScope(); }
protected override void AddBindings(IKernel ninjectKernel) { base.AddBindings(ninjectKernel); //要支持Oralce数据库,请在""中填写Oralce库的Schema名称 //如果业务系统自身的表在同一库中,则需要继承ModelContext创建新的Context, 并如下写法: //ninjectKernel.Rebind<ModelContext,DbContext>().To<YourContext>() //.WithPropertyValue("Schema", ""); ninjectKernel.Rebind <ModelContext>().ToSelf() .WithPropertyValue("Schema", ""); //如果要修改上传根目录,请恢复以下代码,并修改第二个参数 //既支持物理路径(如 D:\UploadFiles),也支持虚拟路径 如"~/UploadFiles" //ninjectKernel.Rebind<IFileLocator>().To(typeof(FileLocator)) // .WithConstructorArgument("rootPath", "~/UploadFiles"); //如果要开启多标签,或修改默认皮肤,请恢复以下代码,并修改第二个参数 ninjectKernel.Rebind <UserConfig>().ToSelf() .WithPropertyValue("ShowTab", false) //如果需要系统默认以多标签形式显示 页,请设置为true .WithPropertyValue("Theme", "blue") //系统默认皮肤 .WithPropertyValue("GridLineStyle", GridLineStyle.Horizental); //表格线设置 //todo: 额外的注入代码 ninjectKernel.Bind <IMenuExtInfoService>().To <TempMenuExtInfoService>(); }
/// <summary> /// Configures object to json mapping /// </summary> /// <typeparam name="T">Domain object type</typeparam> /// <typeparam name="TMapper">Mapper object type</typeparam> /// <param name="kernel">Ninject kernel object</param> /// <returns>JsonMapperConfiguration for further mapping customization</returns> public static JsonMapperConfiguration <T> ConfigureMapping <T, TMapper>(this IKernel kernel) where TMapper : JsonMapper <T> { if (kernel == null) { throw new ArgumentNullException("kernel"); } // create and rebind mapping configuration var configuration = kernel.Get <JsonMapperConfiguration <T> >(); kernel.Rebind <JsonMapperConfiguration <T> >().ToConstant(configuration); // create and rebind mapper object var mapper = kernel.Get <TMapper>(); kernel.Rebind <IJsonMapper <T> >().ToConstant(mapper); // add mapper to the manager instance var manager = kernel.Get <JsonMapperManager>(); manager.AddMapper <T>(mapper); // return configuration object for further customization return(configuration); }
/// <summary> /// 加入注入服务绑定 /// </summary> protected override void AddBindings(IKernel ninjectKernel) { base.AddBindings(ninjectKernel); var settings = ConfigurationManager.ConnectionStrings["DefaultConnection"]; if (settings.IsOracleClient()) { var builder = new DbConnectionStringBuilder(); builder.ConnectionString = settings.ConnectionString; var schema = builder["USER ID"].ToString(); //要支持Oralce数据库,请在""中填写Oralce库的Schema名称 ninjectKernel.Rebind <ModelContext>().ToSelf() .WithPropertyValue("Schema", schema); } //如果要修改上传根目录,请恢复以下代码,并修改第二个参数 //ninjectKernel.Rebind<IFileLocator>().To(typeof(FileLocator)) // .WithConstructorArgument("rootPath", "D:\\Temp"); //如果要开启多标签,或修改默认皮肤,请恢复以下代码,并修改第二个参数 //ninjectKernel.Rebind<UserConfig>().ToSelf() //.WithPropertyValue("ShowTab", false) //如果需要系统默认以多标签形式显示页,请设置为true //.WithPropertyValue("Theme", "blue"); //系统默认皮肤 //额外的注入代码 ninjectKernel.Rebind <IStateProvider>().ToConstant(new PKSStateProvider()); }
protected override void PreConfigure(IKernel kernel) { base.PreConfigure(kernel); kernel.Rebind <TFake>().ToConstant(_fake); kernel.Rebind <IEventPublisher <CrashEvent> >().ToConstant(Substitute.For <IEventPublisher <CrashEvent> >()); kernel.Rebind <IMetricsInitializer>().ToConstant(Substitute.For <IMetricsInitializer>()); }
protected override void PreConfigure(IKernel kernel) { base.PreConfigure(kernel); Console.WriteLine($"-----------------------------Silo is RebindForTests"); kernel.Rebind <ServiceValidator>().To <CalculatorServiceHost.MockServiceValidator>().InSingletonScope(); kernel.Rebind <ICertificateLocator>().To <DummyCertificateLocator>().InSingletonScope(); kernel.RebindForTests(); }
protected override void PreConfigure(IKernel kernel, ServiceArguments Arguments) { var env = new HostEnvironment(new TestHostEnvironmentSource(appName: ServiceName)); kernel.Rebind <IEnvironment>().ToConstant(env).InSingletonScope(); kernel.Rebind <CurrentApplicationInfo>().ToConstant(env.ApplicationInfo).InSingletonScope(); base.PreConfigure(kernel, Arguments); }
public static async Task SetupAuditRepository( Mock <IWorkspaceAuditService> workspaceAuditService, Mock <IViewRepository> viewRepository, Mock <IViewCriteriaRepository> viewCriteriaRepository, Mock <IWorkspaceAuditServiceFactory> workspaceAuditServiceFactory, IKernel kernel, Hour hour) { // Get the database servers and workspaceIds var serverRepo = kernel.Get <IServerRepository>(); var servers = await serverRepo.ReadAllActiveAsync(); var databaseServers = servers.Where(s => s.ServerType == ServerType.Database); var workspaceIdsTask = await databaseServers.Select(s => serverRepo.ReadServerWorkspaceIdsAsync(s.ServerId)).WhenAllStreamed(); var workspaceIds = workspaceIdsTask.SelectMany(wids => wids).ToList(); // Divide up the total number of mock audits per workspace var totalWorkspaceAudits = totalAudits / workspaceIds.Count; // Create a list of mock user ids var users = Enumerable.Range(0, totalUsers) .Select(i => i).ToList(); // Setup all the methods of the workspaceAuditService to return mock data workspaceAuditService.Setup(r => r.ReadAuditsAsync(It.IsAny <int>(), It.IsAny <DateTime>(), It.IsAny <DateTime>(), It.IsAny <IList <AuditActionId> >(), It.IsAny <int>(), It.IsAny <long>())) .ReturnsAsync <int, DateTime, DateTime, IList <AuditActionId>, int, long, IWorkspaceAuditService, IList <Audit> >((wid, sd, ed, was, size, start) => Audits(wid, size, start, hour)); workspaceAuditService.Setup(r => r.ReadTotalAuditExecutionTimeForHourAsync(It.IsAny <int>(), It.IsAny <DateTime>(), It.IsAny <DateTime>(), It.IsAny <IList <AuditActionId> >())) .ReturnsAsync(totalWorkspaceAudits * (2500 / 2)); workspaceAuditService.Setup(r => r.ReadTotalAuditsForHourAsync(It.IsAny <int>(), It.IsAny <DateTime>(), It.IsAny <DateTime>(), It.IsAny <IList <AuditActionId> >())) .ReturnsAsync(totalWorkspaceAudits); workspaceAuditService.Setup(r => r.ReadTotalLongRunningQueriesForHourAsync(It.IsAny <int>(), It.IsAny <DateTime>(), It.IsAny <DateTime>(), It.IsAny <IList <AuditActionId> >())) .ReturnsAsync(totalWorkspaceAudits / 10); workspaceAuditService.Setup(r => r.ReadUniqueUsersForHourAuditsAsync(It.IsAny <int>(), It.IsAny <DateTime>(), It.IsAny <DateTime>(), It.IsAny <IList <AuditActionId> >())) .ReturnsAsync(users); // Setup search repository methods to return mock data viewRepository.Setup(r => r.ReadById(It.IsAny <int>(), It.IsAny <int>())) .Returns <int, int>((wid, sid) => AuditSearchTestCase(sid, 2, wid, 750)); viewCriteriaRepository.Setup(r => r.ReadViewCriteriasForSearch(It.IsAny <int>(), It.Is <int>(i => i % 100 == 0))) .Returns <int, int>((wid, sid) => new[] { new ViewCriteria { IsSubSearch = true, Operator = "", Value = $"{sid + 1}" } }); viewCriteriaRepository.Setup(r => r.ReadViewCriteriasForSearch(It.IsAny <int>(), It.Is <int>(i => i % 100 != 0))) .Returns(new[] { new ViewCriteria { IsSubSearch = false, Operator = "like", Value = "%Something really cool%" } }); // Have the factory return the mocked workspaceAuditService workspaceAuditServiceFactory.Setup(f => f.GetAuditService(It.IsAny <int>(), It.IsAny <int>())) .ReturnsAsync(workspaceAuditService.Object); // Rebind the kernel to return the mocked objects instead kernel.Rebind <IWorkspaceAuditService>().ToConstant(workspaceAuditService.Object); kernel.Rebind <IViewRepository>().ToConstant(viewRepository.Object); kernel.Rebind <IViewCriteriaRepository>().ToConstant(viewCriteriaRepository.Object); kernel.Rebind <IWorkspaceAuditServiceFactory>().ToConstant(workspaceAuditServiceFactory.Object); }
public void RegisterComponents(IKernel container) { container.Rebind<IEventManager>().ToConstant(eventManager); container.Rebind<ILogger>().ToConstant(logger); container.Bind<QcConfiguration>().ToConstant(configuration); container.Bind<StartupChecker>().To<StartupChecker>(); startupChecker = container.Get<StartupChecker>(); }
protected override void PreConfigure(IKernel kernel) { base.PreConfigure(kernel); kernel.Rebind <TFake>().ToConstant(_fake); kernel.Rebind <IEventPublisher <CrashEvent> >().ToConstant(Substitute.For <IEventPublisher <CrashEvent> >()); kernel.Rebind <ICertificateLocator>().To <DummyCertificateLocator>().InSingletonScope(); kernel.Rebind <IMetricsInitializer>().ToConstant(Substitute.For <IMetricsInitializer>()); }
/// <summary> /// Configures the facade with the supplied <see cref="IQueryfyConfiguration"/>. /// </summary> /// <param name="configuration">The <see cref="IQueryfyConfiguration"/>.</param> /// <exception cref="ArgumentNullException">The value of '<paramref name="configuration"/>' cannot be null. </exception> public static void ConfigureWith([NotNull] IQueryfyConfiguration configuration) { if (configuration == null) { throw new ArgumentNullException(nameof(configuration)); } Kernel.Rebind <IQueryfyConfiguration>().ToConstant(configuration).InSingletonScope(); }
/// <summary> /// Registers the specified instance. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="instance">The instance.</param> /// <param name="name">The name.</param> public void Register <T>(T instance, string name = null) where T : class { var binding = _kernel.Rebind <T>().ToConstant(instance); if (name != null) { binding.Named(name); } }
public void ChangeMediaType(Enums.EMediaType mediaType) { var configurationService = _Kernel.Get <IConfigurationService>(); configurationService.MediaType = mediaType; _Kernel.Rebind <IConfigurationService>().ToConstant(configurationService); BindSelector(configurationService); Console.WriteLine("Media type has been changed to: {0}.", configurationService.MediaType); }
/// <summary> /// Load your modules or register your services here! /// </summary> /// <param name="kernel">The kernel.</param> private static void RegisterServices(IKernel kernel) { var VehicleModelService = kernel.Get <Projekt.Service.Interface.IVehicleModelService>(); kernel.Rebind <Projekt.Service.Interface.IVehicleModelService>().To(VehicleModelService.GetType()); var VehicleMakeService = kernel.Get <Projekt.Service.Interface.IVehicleMakeService>(); kernel.Rebind <Projekt.Service.Interface.IVehicleMakeService>().To(VehicleMakeService.GetType()); }
protected override void RegisterServices(IKernel kernel) { kernel.Rebind <CartModel>().ToMethod(context => context.Kernel.Get <ICartBuilder>().BuildCart()).InRequestScope(); kernel.Rebind <SECVPN>().ToMethod(context => { var service = new SECVPNClient(new BasicHttpBinding(BasicHttpSecurityMode.Transport), new EndpointAddress("https://www.secpay.com/java-bin/services/SECCardService")); return(service); }); }
protected override void RegisterServices(IKernel kernel) { kernel.Rebind<CartModel>().ToMethod(context => context.Kernel.Get<ICartBuilder>().BuildCart()).InRequestScope(); kernel.Rebind<SECVPN>().ToMethod(context => { var service = new SECVPNClient(new BasicHttpBinding(BasicHttpSecurityMode.Transport), new EndpointAddress("https://www.secpay.com/java-bin/services/SECCardService")); return service; }); }
protected override void PreConfigure(IKernel kernel, ServiceArguments Arguments) { var env = environment ?? new HostEnvironment(new TestHostEnvironmentSource( zone: "zone", deploymentEnvironment: "env", appName: "ICalculatorService")); kernel.Rebind <IEnvironment>().ToConstant(env).InSingletonScope(); kernel.Rebind <CurrentApplicationInfo>().ToConstant(env.ApplicationInfo).InSingletonScope(); base.PreConfigure(kernel, Arguments); }
protected override void PreConfigure(IKernel kernel, ServiceArguments Arguments) { var env = new HostEnvironment(new TestHostEnvironmentSource()); kernel.Rebind <IEnvironment>().ToConstant(env).InSingletonScope(); kernel.Rebind <CurrentApplicationInfo>().ToConstant(env.ApplicationInfo).InSingletonScope(); base.PreConfigure(kernel, Arguments); Console.WriteLine($"-----------------------------Silo is RebindForTests"); kernel.Rebind <ServiceValidator>().To <CalculatorServiceHost.MockServiceValidator>().InSingletonScope(); kernel.RebindForTests(); }
public static void SetTaxSettings(this IKernel kernel, bool taxesEnabled = false, bool loadedPricesIncludeTax = false, bool shippingTaxesEnabled = false, bool shippingPricesIncludeTax = false) { var taxSettings = new TaxSettings { TaxesEnabled = taxesEnabled, LoadedPricesIncludeTax = loadedPricesIncludeTax, ShippingRateTaxesEnabled = shippingTaxesEnabled, ShippingRateIncludesTax = shippingPricesIncludeTax }; kernel.Rebind <TaxSettings>().ToConstant(taxSettings); kernel.Rebind <IProductPricingService>().ToConstant(new ProductPricingService(taxSettings)); }
/// <summary> /// Used to configure Kernel in abstract base-classes, which should apply to any concrete service that inherits from it. /// Should be overridden when creating a base-class that should include common behaviour for a family of services, without /// worrying about concrete service authors forgetting to call base.Configure(). Nevertheless, when overriding this method, /// you should always call base.PreConfigure(), and if all inheritors of the class are concrete services, you should also /// mark this method as sealed to prevent confusion with Configure(). /// </summary> /// <param name="kernel">Kernel that should contain bindings for the service.</param> protected virtual void PreConfigure(IKernel kernel, ServiceArguments Arguments) { kernel.Rebind <IActivator>().To <InstanceBasedActivator <TInterface> >().InSingletonScope(); kernel.Rebind <IServiceInterfaceMapper>().To <IdentityServiceInterfaceMapper>().InSingletonScope().WithConstructorArgument(typeof(TInterface)); kernel.Load <MicrodotModule>(); kernel.Load <MicrodotHostingModule>(); kernel.Bind <IRequestListener>().To <HttpServiceListener>(); GetLoggingModule().Bind(kernel.Rebind <ILog>(), kernel.Rebind <IEventPublisher>(), kernel.Rebind <Func <string, ILog> >()); kernel.Rebind <ServiceArguments>().ToConstant(Arguments).InSingletonScope(); }
public void RegisterComponents(IKernel container) { container.Rebind<IEventManager>().ToConstant(eventManager); container.Bind<IVersionOneProcessor>().ToConstant(v1Processor); container.Rebind<ILogger>().To<Logger>(); container.Bind<WorkitemWriterServiceConfiguration>().ToConstant(configuration); container.Bind<IWorkitemWriter>().To<WorkitemWriter>(); container.Bind<IWorkitemReader>().To<WorkitemReader>(); workitemWriter = container.Get<IWorkitemWriter>(); workitemReader = container.Get<IWorkitemReader>(); externalWorkitemQuerier = container.Get<ClosedExternalWorkitemQuerier>(); startupChecker = container.Get<StartupChecker>(); }
public void OnLoad(IKernel kernel) { kernel.Bind(x => x.FromThisAssembly().SelectAllClasses().BindAllInterfaces()); kernel.Bind(x => x.FromAssemblyContaining <SonosPlayer>().SelectAllClasses().BindAllInterfaces()); kernel.Rebind <IIdentityProvider>().To <GuidIdentityProvider>().InSingletonScope(); kernel.Rebind <ServerConfiguration>().ToMethod(x => ServerConfigurationFactory.LoadConfiguration()).InSingletonScope(); SmapiSoapController.MusicRepository = () => kernel.Get <IMusicRepository>(); SmapiSoapController.IdentityProvider = () => kernel.Get <IIdentityProvider>(); kernel.Bind <ServerBuilder>().ToMethod(context => new ServerBuilder(typeof(SmapiSoapController))); }
protected override void PreConfigure(IKernel kernel) { base.PreConfigure(kernel); kernel.Rebind <ServiceValidator>().To <MockServiceValidator>().InSingletonScope(); kernel.Rebind <ISingletonDependency>().To <SingletonDependency>().InSingletonScope(); Func <GrainLoggingConfig> writeGrainLog = () => new GrainLoggingConfig { LogMicrodotGrains = true, LogRatio = 1, LogServiceGrains = true, LogOrleansGrains = true }; kernel.Rebind <Func <GrainLoggingConfig> >().ToConstant(writeGrainLog); kernel.RebindForTests(); Kernel = kernel; }
public static void Init(IKernel kernel) { AutoVersionsDBSettings setting = new AutoVersionsDBSettings(@"[CommonApplicationData]\AutoVersionsDB.IntegrationTests"); kernel.Bind <AutoVersionsDBSettings>().ToConstant(setting); MockConsoleError = new Mock <IStandardStreamWriter>(); MockConsoleOut = new Mock <IStandardStreamWriter>(); MockConsole = new Mock <IConsoleExtended>(); MockConsole.Setup(m => m.Error).Returns(MockConsoleError.Object); MockConsole.Setup(m => m.Out).Returns(MockConsoleOut.Object); kernel.Bind <IConsoleExtended>().ToConstant(MockConsole.Object); ConsoleProcessMessages internalConsoleProcessMessages = kernel.Get <ConsoleProcessMessages>(); MockConsoleProcessMessages = new Mock <ConsoleProcessMessagesForTests>(MockBehavior.Strict, internalConsoleProcessMessages); kernel.Rebind <IConsoleProcessMessages>().ToConstant(MockConsoleProcessMessages.Object); NotificationsViewModel internalNotificationsViewModel = kernel.Get <NotificationsViewModel>(); MockNotificationsViewModel = new Mock <NotificationsViewModelForTests>(MockBehavior.Strict, internalNotificationsViewModel); kernel.Rebind <INotificationsViewModel>().ToConstant(MockNotificationsViewModel.Object); DBVersionsViewSateManager internalDBVersionsViewSateManager = kernel.Get <DBVersionsViewSateManager>(); MockDBVersionsViewSateManagerFotTests = new Mock <DBVersionsViewSateManagerForTests>(MockBehavior.Strict, internalDBVersionsViewSateManager); kernel.Rebind <IDBVersionsViewSateManager>().ToConstant(MockDBVersionsViewSateManagerFotTests.Object); EditProjectViewSateManager internalEditProjectViewSateManager = kernel.Get <EditProjectViewSateManager>(); MockEditProjectViewSateManagerFotTests = new Mock <EditProjectViewSateManagerForTests>(MockBehavior.Strict, internalEditProjectViewSateManager); kernel.Rebind <IEditProjectViewSateManager>().ToConstant(MockEditProjectViewSateManagerFotTests.Object); MockOsProcessUtils = new Mock <OsProcessUtils>(); kernel.Bind <OsProcessUtils>().ToConstant(MockOsProcessUtils.Object); MockOsProcessUtils .Setup(m => m.StartOsProcess(It.IsAny <string>())) .Callback <string>((filename) => { //Do nothing }); UIGeneralEvents.OnException += UIGeneralEvents_OnException; }
public void OnLoad(IKernel kernel) { kernel.Bind(x => x.FromThisAssembly().SelectAllClasses().BindAllInterfaces()); kernel.Bind(x => x.FromAssemblyContaining<SonosPlayer>().SelectAllClasses().BindAllInterfaces()); kernel.Bind(x => x.FromAssemblyContaining<IFileSystem>().SelectAllClasses().BindAllInterfaces()); kernel.Rebind<ServerConfiguration>().ToMethod(x => ServerConfigurationFactory.LoadConfiguration()).InSingletonScope(); kernel.Rebind<IIdentityProvider>().To<IdentityProvider>().InSingletonScope(); kernel.Rebind<ISearchProvider>().To<TopLevelDirectorySearchProvider>().InSingletonScope(); kernel.Rebind<SmapiSoapControllerDependencies>().To<SmapiSoapControllerDependencies>().InSingletonScope(); SmapiSoapController.Dependencies = () => kernel.Get<SmapiSoapControllerDependencies>(); kernel.Bind<LocalMusicServerFactory>().ToMethod(context => new LocalMusicServerFactory(typeof(SmapiSoapController))); }
/// <summary> /// Load your modules or register your services here! /// </summary> /// <param name="kernel">The kernel.</param> private static void RegisterServices(IKernel kernel) { //kernel.Bind<Cart.Common.ICartInterceptor>().To<GreedyInterceptor>(); //Note: This isn't a good way to obtain the Cart Service implementation type. This is Ninject limitation. var cartService = kernel.Get<Cart.Service.Common.ICartService>(); kernel.Rebind<Cart.Service.Common.ICartService>().To(cartService.GetType()).Intercept().With<GreedyInterceptor>(); }
public void Process(Type type, Func<IContext, object> scopeCallback, IKernel kernel) { if (NoBindingsIn(kernel)) { kernel.Rebind(_service).To(type).InScope(scopeCallback).WithMetadata("assembly", Assembly(type)); return; } if (DefaultBindingIn(kernel) && Assembly(type) != _serviceAssembly) { kernel.Rebind(_service).To(type).InScope(scopeCallback).WithMetadata("assembly", Assembly(type)); return; } kernel.Bind(_service).To(type).InScope(scopeCallback).WithMetadata("assembly", Assembly(type)); }
public NhBlogServiceTests() { _kernel = new StandardKernel(); _kernel.Load(new NinjectModules()); _kernel.Load(new NhNinjectModule()); _kernel.Rebind<IBlogRepository>().To<NhBlogRepository>(); }
public void SetUp() { _view = MockRepository.GenerateMock<ICradiatorView>(); _configSettings = MockRepository.GenerateMock<IConfigSettings>(); _configSettings.Expect(c => c.ProjectNameRegEx).Return(".*").Repeat.Any(); _configSettings.Expect(c => c.CategoryRegEx).Return(".*").Repeat.Any(); _skinLoader = MockRepository.GenerateMock<ISkinLoader>(); _screenUpdater = MockRepository.GenerateMock<IScreenUpdater>(); _configFileWatcher = MockRepository.GenerateMock<IConfigFileWatcher>(); var bootstrapper = new Bootstrapper(_configSettings, _view); _kernel = bootstrapper.CreateKernel(); _kernel.Rebind<ISkinLoader>().ToConstant(_skinLoader); _kernel.Rebind<IScreenUpdater>().ToConstant(_screenUpdater); _kernel.Rebind<IConfigFileWatcher>().ToConstant(_configFileWatcher); }
public override void SetupBindings(IKernel kernel, Func<string, Type> lookupType, Func<IContext, object> currentGameScope) { if (!string.IsNullOrEmpty(this.MovementControllerImplementation)) { kernel.Rebind<IMovementController>() .To(lookupType(this.MovementControllerImplementation)) .InTransientScope(); } }
/// <summary> /// Load your modules or register your services here! /// </summary> /// <param name="kernel">The kernel.</param> private static void RegisterServices(IKernel kernel) { var namespaces = new string[] { "HappyPath.*" }; kernel.Bind(x => x .FromAssembliesMatching(namespaces) .SelectAllClasses() .BindAllInterfaces() ); kernel.Rebind<IMappingEngine>().ToMethod(x => Mapper.Engine); kernel.Rebind<IHappyPathSession>().To<HappyPathSession>() .InRequestScope(); AutoMapperConfiguration.Configure(kernel); }
public FlowForm( IKernel kernel, IFormFactory formFactory, IStorageAccess storageAccess, Lazy<FlowProcessingPipeline> flowProcessingPipeline) { // TODO: Expose this in the UI. this.Seed = 0xDEADBEEF; this.InitializeComponent(); kernel.Rebind<IRenderingLocationProvider>().ToMethod(context => this); kernel.Rebind<ICurrentWorldSeedProvider>().ToMethod(context => this); this.m_FlowProcessingPipeline = flowProcessingPipeline.Value; this.m_FormFactory = formFactory; this.m_StorageAccess = storageAccess; if (this.m_FlowProcessingPipeline == null) throw new Exception("IFlowProcessingPipeline is not of type FlowProcessingPipeline."); this.m_FlowProcessingPipeline.FormConnect(this); this.CreateAnalysisActions(); this.UpdateStatusArea(); }
/// <summary> /// Load your modules or register your services here! /// </summary> /// <param name="kernel">The kernel.</param> private static void RegisterServices(IKernel kernel) { kernel.Bind(x => x.FromAssemblyContaining( typeof(IEventLogController), typeof(ITriageDbContext), typeof(NinjectWebCommon)) .SelectAllClasses() .BindDefaultInterfaces() ); kernel.Rebind<ITriageDbContextFactory>().To<TriageDbContextFactory>().InSingletonScope(); }
protected override void ConfigureApplicationContainer(IKernel existingContainer) { ContainerBootstrapper .Bootstrap(existingContainer) .Analyze(x => x.AssembiesContaining(new[] { typeof(CoreAssemblyMarker), typeof(DroneAssemblyMarker), typeof(IRestClient), typeof(IDocumentStore) })) .BindInterfaceToDefaultImplementation() .Configure(x => x.InTransientScope()) .NoDatabase() .Settings(x => x.UseJsonFiles()) .Done(); existingContainer.Rebind<IScheduler>().ToConstant(_scheduler); var settings =typeof(CoreAssemblyMarker).Assembly.GetExportedTypes().Where(type => type.Name.EndsWith("Settings")).ToList(); settings.ForEach(x=> existingContainer.Rebind(x).ToConstant(_kernel.Get(x))); }
public void Init() { fixture = new Fixture().Customize(new AutoMoqCustomization()); mockDice = fixture.Create<Mock<Dice>>(); ninject = new StandardKernel(new BindingsModule()); ninject.Rebind<IDice>().ToConstant(mockDice.Object); turnHandler = ninject.Get<TurnHandler>(); player1 = ninject.Get<IPlayer>(); player2 = ninject.Get<IPlayer>(); realtor = ninject.Get<IRealtor>(); jailer = ninject.Get<IJailer>(); }
public void Init() { fixture = new Fixture().Customize(new AutoMoqCustomization()); ninject = new StandardKernel(new BindingsModule()); mockChanceDeck = fixture.Create<Mock<Deck>>(); mockChestDeck = fixture.Create<Mock<Deck>>(); mockDeckFactory = fixture.Create<Mock<DeckFactory>>(); mockDeckFactory.Setup(x => x.BuildChanceDeck()).Returns(mockChanceDeck.Object); mockDeckFactory.Setup(x => x.BuildCommunitiyChestDeck()).Returns(mockChestDeck.Object); ninject.Rebind<IDeckFactory>().ToConstant(mockDeckFactory.Object).InSingletonScope(); cardHandler = ninject.Get<CardHandler>(); }
/// <summary> /// Load your modules or register your services here! /// </summary> /// <param name="kernel">The kernel.</param> private static void RegisterServices(IKernel kernel) { var assemblies = new[] { Assembly.GetExecutingAssembly(), Assembly.GetAssembly(typeof(IHostApplication)), Assembly.GetAssembly(typeof(InspectionBase)), Assembly.GetAssembly(typeof(IRubberduckParser)) }; ApplyDefaultInterfacesConvention(kernel, assemblies); kernel.Rebind<ISinks>().ToConstant(Sinks); kernel.Bind<RubberduckParserState>().ToSelf().InCallScope(); kernel.Bind<RubberduckParser>().ToSelf().InCallScope(); BindCodeInspectionTypes(kernel); }
public void OnLoad(IKernel kernel) { kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel); kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>(); kernel.Bind<HttpContextBase>().ToMethod(x=> new HttpContextWrapper(kernel.Get<HttpContext>())); kernel.Bind(x => x.FromThisAssembly().SelectAllClasses().BindDefaultInterfaces()); kernel.Bind(x => x.FromAssemblyContaining<IFileSystem>().SelectAllClasses().BindDefaultInterfaces()); kernel.Rebind<ICurrentUserSession>().ToProvider<CurrentUserSessionProvider>(); kernel.Bind<IJustGivingClient>().ToProvider<JustGivingClientProvider>(); kernel.Bind<IRequestBuilder<Registration, CreateAccountRequest>>().To<CreateAccountRequestBuilder>(); kernel.Bind<IRequestBuilder<PageRegistration, RegisterPageRequest>>().To<RegisterPageRequestBuilder>(); AuthenticatedUserOnlyAttribute.GetCurrentUserSession = () => kernel.Get<ICurrentUserSession>(); }
/// <summary> /// Load your modules or register your services here! /// </summary> /// <param name="kernel">The kernel.</param> private static void RegisterServices( IKernel kernel ) { string path = new Uri( Path.GetDirectoryName( typeof( NinjectWebCommon ).Assembly.CodeBase ) ?? "" ).LocalPath; string thisNamespace = typeof( NinjectWebCommon ).FullName.Split( new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries )[0]; // FRAGILE: ASSUME: All our code is in this namespace kernel.Bind( x => x .FromAssembliesInPath( path ) // Blows with "not marked as serializable": , a => a.FullName.StartsWith( assemblyPrefix ) ) .Select( type => type.IsClass && !type.IsAbstract && type.FullName.StartsWith( thisNamespace ) ) // .SelectAllClasses() wires up everyone else's stuff too .BindDefaultInterface() .Configure( b => b.InRequestScope() ) ); // Add other bindings as necessary kernel.Rebind<IBetaSigmaPhiContext>().ToMethod( _ => (IBetaSigmaPhiContext)kernel.GetService( typeof(BetaSigmaPhiContext) ) ); // Initialize the service locator ServiceLocator.Initialize( kernel.GetService ); }
public static void Initialize(IVisualStudioWriter visualStudioWriter, IVisualStudioEventProxy visualStudioEventProxy, ICodeBehindFileHelper codeBehindFileHelper, ISolutionFileReader dteSolutionFileReader) { Kernel = new StandardKernel( new StandardModule(), new pMixinsStandardModule()); Kernel.Bind<IVisualStudioWriter>().ToMethod(c => visualStudioWriter).InSingletonScope(); Kernel.Bind<IVisualStudioEventProxy>().ToMethod(c => visualStudioEventProxy).InSingletonScope(); Kernel.Bind<ICodeBehindFileHelper>().ToMethod(c => codeBehindFileHelper); Kernel.Rebind<ISolutionFileReader>().ToMethod(c => dteSolutionFileReader); LoggingActivity.Initialize(visualStudioWriter); //Make sure the VisualStudioOpenDocumentManager loads early Kernel.Get<IVisualStudioOpenDocumentManager>(); }
public override void MainSetup() { TestSpecificKernel = KernelFactory.BuildDefaultKernelForTests(); EventProxy = TestSpecificKernel.Get<IVisualStudioEventProxy>() //This is important, if the casting isn't done, then EventProxy isn't returned via IoC as TestVisualStudioEventProxy; _MockFileWrapper = BuildMockFileReader(); TestSpecificKernel.Rebind<IFileWrapper>().ToMethod(c => _MockFileWrapper); _MockMicrosoftBuildProjectLoader = BuildMockMicrosoftBuildProjectLoader(); TestSpecificKernel.Rebind<IMicrosoftBuildProjectLoader>().ToMethod(c => _MockMicrosoftBuildProjectLoader); _MockCodeBehindFileHelper = BuildMockCodeBehindFileHelper(); TestSpecificKernel.Rebind<ICodeBehindFileHelper>().ToMethod(c => _MockCodeBehindFileHelper); _MockSolution = new MockSolution(); //Set solution context TestSpecificKernel.Get<ISolutionContext>().SolutionFileName = _MockSolution.FileName; }
/// <summary> /// Processes the specified type creating kernel bindings. /// If the type is called typeName and implements interfaceType it will be bound to interfaceType /// </summary> /// <param name = "type">The type to process.</param> /// <param name = "scopeCallback">the scope callback.</param> /// <param name = "kernel">The kernel to configure.</param> public void Process(Type type, Func<IContext, object> scopeCallback, IKernel kernel) { if (type.IsInterface || type.IsAbstract) { return; } if (TypeName.Equals(type.Name) || TypeName.Equals(type.FullName)) if (type.GetInterface(InterfaceType.FullName) != null) kernel.Rebind(InterfaceType).To(type).InScope(scopeCallback); }
public void Init() { var fixture = new Fixture().Customize(new AutoMoqCustomization()); mockDeck = fixture.Create<Mock<IDeck>>(); mockDice = fixture.Create<Mock<Dice>>(); mockDeckFactory = fixture.Create<Mock<IDeckFactory>>(); mockPlayer = fixture.Create<Mock<IPlayer>>(); ninject = new StandardKernel(new BindingsModule()); ninject.Rebind<IDice>().ToConstant(mockDice.Object).InSingletonScope(); ninject.Rebind<IDeckFactory>().ToConstant(mockDeckFactory.Object).InSingletonScope(); ninject.Rebind<ITaskHandler>().To<TaskHandler>().WithConstructorArgument(PlayerFactory.BuildPlayers(6)); // register six OTHER players mockDeckFactory.Setup(x => x.BuildChanceDeck()).Returns(mockDeck.Object); mockDeckFactory.Setup(x => x.BuildCommunitiyChestDeck()).Returns(mockDeck.Object); turnHandler = ninject.Get<ITurnHandler>(); player = ninject.Get<IPlayer>(); realtor = ninject.Get<IRealtor>(); jailer = ninject.Get<IJailer>(); taskHandler = ninject.Get<ITaskHandler>(); }
protected override void ConfigureApplicationContainer(IKernel existingContainer) { _action(existingContainer); existingContainer.Rebind<IScheduler>().ToConstant(_scheduler); }
public void RegisterComponents(IKernel container) { var connector = new JiraConnectorFactory(JiraConnectorType.Rest).Create(jiraConfig.Url, jiraConfig.UserName, jiraConfig.Password); container.Rebind<IEventManager>().ToConstant(eventManager); container.Rebind<ILogger>().ToConstant(logger); container.Bind<IJiraConnector>().ToConstant(connector); container.Bind<JiraServiceConfiguration>().ToConstant(jiraConfig); container.Bind<IJiraIssueProcessor>().To<JiraIssueReaderUpdater>(); container.Bind<StartupChecker>().To<StartupChecker>(); startupChecker = container.Get<StartupChecker>(); jiraProcessor = container.Get<IJiraIssueProcessor>(); }
protected override void ConfigureApplicationContainer(IKernel existingContainer) { ContainerBootstrapper .Bootstrap(existingContainer) .Analyze(x => x.AssembiesContaining(new[] { typeof(CoreAssemblyMarker), typeof(ServiceAssemblyMarker), typeof(IRestClient) })) .BindInterfaceToDefaultImplementation() .Configure(x => x.InTransientScope()) .Storage<IDocumentStore>(x => x.Constant(_documentStore)) .Settings(x => x.UseDocumentDatabase()) .Done(); existingContainer.Rebind<IScheduler>().ToProvider<QuartzSchedulerProvider>().InTransientScope(); }
/// <summary> /// Load your modules or register your services here! /// </summary> /// <param name="kernel">The kernel.</param> private static void RegisterServices(IKernel kernel) { var eventService = kernel.Get<EventManager.Service.Common.IEventService>(); kernel.Rebind<EventManager.Service.Common.IEventService>().To(eventService.GetType()); }
public void Load(IKernel kernel) { kernel.Rebind<IDebugRenderer>().To<DefaultDebugRenderer>().InSingletonScope(); }