public void Register(SimpleInjector.Container container) { container.RegisterSingle <ISubService, SubService>(); container.RegisterSingle <ISubDao, SubDao>(); container.RegisterSingle <IPostService, PostService>(); container.RegisterSingle <IPostDao, PostDao>(); }
/// <summary> /// Registers the views. /// </summary> /// <param name="container">The container.</param> #region Methods private void RegisterViews(Container container) { container.Register <MainWindow>(); container.Register <ThemeControlView>(); container.Register <LanguageControlView>(); container.Register <MainControlView>(); container.Register <GameControlView>(); container.Register <InstalledModsControlView>(); container.Register <SortOrderControlView>(); container.Register <ModHolderControlView>(); container.Register <SearchModsControlView>(); container.Register <CollectionModsControlView>(); container.Register <AddNewCollectionControlView>(); container.Register <ExportModCollectionControlView>(); container.Register <MainConflictSolverControlView>(); container.Register <MergeViewerControlView>(); container.Register <ModCompareSelectorControlView>(); container.Register <MergeViewerBinaryControlView>(); container.Register <ModConflictIgnoreControlView>(); container.Register <ModifyCollectionControlView>(); container.Register <OptionsControlView>(); container.Register <ConflictSolverModFilterControlView>(); container.Register <ConflictSolverResetConflictsControlView>(); container.Register <ConflictSolverDBSearchControlView>(); container.Register <ConflictSolverCustomConflictsControlView>(); container.Register <ActionsControlView>(); container.Register <HashReportControlView>(); container.Register <DLCManagerControlView>(); container.Register <PatchModControlView>(); }
static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); var ts = new TraceSource("rskb.application", SourceLevels.All); var di = new SimpleInjector.Container(); ts.TraceInformation("Build"); var blackboxfolderpath = ConfigurationManager.AppSettings["blackboxfolderpath"]; di.RegisterSingle<IBlackBox>(() => new FileBlackBox(blackboxfolderpath)); di.RegisterSingle(typeof (IBoardPortal), typeof (BoardPortal)); di.RegisterSingle(typeof(IBoardProvider2), typeof(EventstoreBoardprovider)); di.RegisterSingle(typeof(IBoard2), typeof(Board2)); di.RegisterSingle(typeof (IBoardController), typeof (BoardController2)); var prov = di.GetInstance<IBoardProvider2>(); var portal = di.GetInstance<IBoardPortal>(); var ctl = di.GetInstance<IBoardController>(); ts.TraceInformation("Bind"); portal.On_card_moved += ctl.Move_card; portal.On_new_card += ctl.Create_card; portal.On_refresh += ctl.Refresh; ctl.On_cards_changed += portal.Display_cards; ts.TraceInformation("Run"); Start(prov, portal); ts.TraceInformation("Show"); Application.Run(portal as Form); }
private static void set_hash_provider(ChocolateyConfiguration config, Container container) { if (!config.Features.UseFipsCompliantChecksums) { var hashprovider = container.GetInstance <IHashProvider>(); try { hashprovider.set_hash_algorithm(CryptoHashProviderType.Md5); } catch (Exception ex) { if (!config.CommandName.is_equal_to("feature")) { if (ex.InnerException != null && ex.InnerException.Message.contains("FIPS")) { "chocolatey".Log().Warn(ChocolateyLoggers.Important, @" FIPS Mode detected - run 'choco feature enable -n {0}' to use Chocolatey.".format_with(ApplicationParameters.Features.UseFipsCompliantChecksums)); var errorMessage = "When FIPS Mode is enabled, Chocolatey requires {0} feature also be enabled.".format_with(ApplicationParameters.Features.UseFipsCompliantChecksums); if (string.IsNullOrWhiteSpace(config.CommandName)) { "chocolatey".Log().Error(errorMessage); return; } throw new ApplicationException(errorMessage); } throw; } } } }
public PersistenceAdapter(PersistenceAdapterSettings settings) { _container = new Container(); _container.Register <CosmosClient>(() => new CosmosClient(settings.AccountEndpoint, settings.AccountKey)); _container.Register <ICourseLoader, CourseLoaderCosmosDb>(); }
private static void Start() { //Inicia a injeção de dependencia container = new SimpleInjector.Container(); NovoIntegra.Application.AutoMapper.AutoMapperConfig.RegisterMappings(); NovoIntegra.Infra.CrossCutting.IoC.BootStrapper.RegisterServices(container); }
static async Task MainAsync(IList <string> csvString, short loanAmount) { var iocContainer = new SimpleInjector.Container(); IoCContainerHelper.AddContainer(iocContainer); var command = iocContainer.GetInstance <IGetBestLoanConditionCommand>(); try { var commandResult = await command.ExecuteAsync(csvString, loanAmount); if (!commandResult.IsSuccess) { Console.WriteLine(commandResult.Error); return; } Console.WriteLine($"Requested amount: £{loanAmount}"); Console.WriteLine($"Rate: {$"{Math.Round(commandResult.Result.Rate, 1):0.0}"}%"); Console.WriteLine($"Monthly repayment: £{Math.Round(commandResult.Result.MonthlyRepayment, 2):0.00}"); Console.WriteLine($"Total repayment: £{Math.Round(commandResult.Result.TotalRepayment, 2):0.00}"); } catch (Exception e) { Console.WriteLine($"Unhandled exception. Message: {e}"); } }
static void Main(string[] args) { var busConfiguration = new EndpointConfiguration("test"); var container = new SimpleInjector.Container(); container.Options.DefaultScopedLifestyle = new ExecutionContextScopeLifestyle(); container.Register(() => new MyService { Id = "Created outside" }, SimpleInjector.Lifestyle.Scoped); busConfiguration.UsePersistence <InMemoryPersistence>(); busConfiguration.EnableInstallers(); busConfiguration.UseContainer <SimpleInjectorBuilder>(customizations: cust => { // which has a higher version than referenced assembly // Assembly 'NServiceBus.SimpleInjector' uses 'SimpleInjector, Version=3.2.7.0, Culture=neutral, PublicKeyToken=984cb50dea722e99' which has a higher version than referenced assembly 'SimpleInjector' with identity 'SimpleInjector, Version=3.2.3.0, Culture=neutral, PublicKeyToken=984cb50dea722e99' cust.UseExistingContainer(container); }); var bus = Endpoint.Create(busConfiguration).Result.Start().Result; { bus.SendLocal(new CreateOrder { }); } Console.ReadLine(); }
public SimpleInjectorScopedContextFactory( SimpleInjector.Container container, INancyContextFactory @default) { this.container = container; defaultFactory = @default; }
static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); var ts = new TraceSource("rskb.application", SourceLevels.All); var di = new SimpleInjector.Container(); ts.TraceInformation("Build"); var blackboxfolderpath = ConfigurationManager.AppSettings["blackboxfolderpath"]; di.RegisterSingle <IBlackBox>(() => new FileBlackBox(blackboxfolderpath)); di.RegisterSingle(typeof(IBoardPortal), typeof(BoardPortal)); di.RegisterSingle(typeof(IBoardProvider2), typeof(EventstoreBoardprovider)); di.RegisterSingle(typeof(IBoard2), typeof(Board2)); di.RegisterSingle(typeof(IBoardController), typeof(BoardController2)); var prov = di.GetInstance <IBoardProvider2>(); var portal = di.GetInstance <IBoardPortal>(); var ctl = di.GetInstance <IBoardController>(); ts.TraceInformation("Bind"); portal.On_card_moved += ctl.Move_card; portal.On_new_card += ctl.Create_card; portal.On_refresh += ctl.Refresh; ctl.On_cards_changed += portal.Display_cards; ts.TraceInformation("Run"); Start(prov, portal); ts.TraceInformation("Show"); Application.Run(portal as Form); }
private void CriaFormIndexacao(int v) { var container = new SimpleInjector.Container(); Infra.CrossCutting.IoC.BootStrapper.RegisterServices(container); container.GetInstance <Imagem_ItapeviContext>().ChangeConnection(ConfigurationManager.ConnectionStrings["PgProdutos"].ToString()); var menuservice = container.GetInstance <ICadastroAppService>(); var atrib = menuservice.ListarAtributos(v); StringBuilder table = new StringBuilder(); table.Append("<input type='hidden' id='qtdeatb' value='" + atrib.Count + "' />"); table.Append("<input type='hidden' id='idcateg' value='" + v.ToString() + "' />"); table.Append("<input type='hidden' id='nmfile' value='" + file + "' />"); foreach (var item in atrib) { table.Append("<tr>"); table.Append("<td>"); table.Append("<span>" + item.TituloAtributo + ": </span>"); table.Append("</td>"); table.Append("<td>"); table.Append("<input type='text' runat='server' id='txt" + item.Ordem + "'>"); table.Append("</td>"); table.Append("</tr>"); } TableAtributos.Text = table.ToString(); }
internal static void InsertIn(SimpleInjector.Container c) { c.Register <SheetEntryRepository>(); c.Register <CategoryRepository>(); c.Register <SheetRepository>(); c.Register <AppOwnerRepository>(); }
public void VerifySignatureTestSetup() { file = new Mock <FileWrapper>(); file.Setup(f => f.ReadAllBytes(It.IsAny <string>())) .Returns <string>(givenFile => files[givenFile]); console = new Mock <ConsoleWrapper>(); Container container = ContainerProvider.GetContainer(); container.Register <FileWrapper>(() => file.Object); container.Register <ConsoleWrapper>(() => console.Object); var asymmetricKeyPairGenerator = new AsymmetricKeyPairGenerator(new SecureRandomGenerator()); var primeMapper = new Rfc3526PrimeMapper(); var curveNameMapper = new FieldToCurveNameMapper(); rsaKeyProvider = new RsaKeyProvider(asymmetricKeyPairGenerator); dsaKeyProvider = new DsaKeyProvider(asymmetricKeyPairGenerator); ecKeyProvider = new EcKeyProvider(asymmetricKeyPairGenerator, curveNameMapper); elGamalKeyProvider = new ElGamalKeyProvider(asymmetricKeyPairGenerator, primeMapper); signatureProvider = new SignatureProvider(new SignatureAlgorithmIdentifierMapper(), new SecureRandomGenerator(), new SignerUtilitiesWrapper()); pkcs8PemFormatter = new Pkcs8PemFormattingProvider(new AsymmetricKeyProvider(new OidToCipherTypeMapper(), new KeyInfoWrapper(), rsaKeyProvider, dsaKeyProvider, ecKeyProvider, elGamalKeyProvider)); base64 = new Base64Wrapper(); encoding = new EncodingWrapper(); random = new SecureRandomGenerator(); }
public void PreencheGrid(int idoper) { var container = new SimpleInjector.Container(); Infra.CrossCutting.IoC.BootStrapper.RegisterServices(container); container.GetInstance <Imagem_ItapeviContext>().ChangeConnection(ConfigurationManager.ConnectionStrings["PgProdutos"].ToString()); var menuserivce = container.GetInstance <ICadastroAppService>(); var user = menuserivce.RetornaUsuario(Session["login"].ToString()); if (!user.Acessos.Any(x => x.id_oper == idoper)) { txtMsgAcessoProibido.Text = "Você não possui acesso a esta categoria."; return; } // string pathmenu = menuserivce.RetornaCaminhoImgens(Convert.ToInt32(idoper)); var categoria = menuserivce.PesquisaCategoria(Convert.ToInt32(idoper)); var query = RetornaQuery(Convert.ToInt32(categoria.id_tipo_arquivo)); if (categoria.id_tipo_arquivo == 1) { Session["dir"] = categoria.PATHIMAGENS; LoadGrid(categoria.PATHIMAGENS, query); } else if (categoria.id_tipo_arquivo == 3) { LoadGridPostgres(idoper, query); } }
public void Main(string[] args) { GCSettings.LatencyMode = GCLatencyMode.SustainedLowLatency; var simpleInjectorContainer = new SimpleInjector.Container(); var autofacBuilder = new ContainerBuilder(); foreach (var type in typeof(Greeter).Assembly.GetTypes()) { autofacBuilder.RegisterType(type); simpleInjectorContainer.Register(type); } simpleInjectorContainer.Verify(); var container = autofacBuilder.Build(); Console.WriteLine("Starting sample performance test"); TimeIt(() => ClassWithDeps.InlinedConstructor(), "Inlined .NET (base line)"); TimeIt(() => ClassWithDeps.Factory(), "Compile Injector (this library)"); TimeIt(() => container.Resolve<ClassWithDeps>(), "Autofac"); TimeIt(() => simpleInjectorContainer.GetInstance<ClassWithDeps>(), "SimpleInjector"); Console.WriteLine("Done"); }
/// <summary> /// Registers the implementations. /// </summary> /// <param name="container">The container.</param> private void RegisterImplementations(Container container) { container.Register <IViewResolver, ViewResolver>(); container.Register <ILogger, Logger>(); container.Register <IAppAction, AppAction>(); container.Register <INotificationAction, NotificationAction>(); container.Register <IFileDialogAction, FileDialogAction>(); container.Register <WritingStateOperationHandler>(SimpleInjector.Lifestyle.Singleton); container.Register <ModDefinitionAnalyzeHandler>(SimpleInjector.Lifestyle.Singleton); container.Register <ModDefinitionLoadHandler>(SimpleInjector.Lifestyle.Singleton); container.Register <ModDefinitionPatchLoadHandler>(SimpleInjector.Lifestyle.Singleton); container.Register <ModDefinitionMergeProgressHandler>(SimpleInjector.Lifestyle.Singleton); container.Register <IShutDownState, ShutdownState>(SimpleInjector.Lifestyle.Singleton); container.Register <OverlayProgressHandler>(SimpleInjector.Lifestyle.Singleton); container.Register <ModFileMergeProgressHandler>(SimpleInjector.Lifestyle.Singleton); container.Register <ActiveGameRequestHandler>(SimpleInjector.Lifestyle.Singleton); container.Register <IUpdater, Updater>(SimpleInjector.Lifestyle.Singleton); container.RemoveMixedLifetimeWarning <IAppAction>(); container.Register <UpdateUnpackProgressHandler>(SimpleInjector.Lifestyle.Singleton); container.Register <GameUserDirectoryChangedHandler>(SimpleInjector.Lifestyle.Singleton); container.Register <ModReportExportHandler>(SimpleInjector.Lifestyle.Singleton); container.Collection.Register(typeof(IFontFamily), new List <Type>() { typeof(NotoSansFontFamily), typeof(NotoSansSCFontFamily) }, SimpleInjector.Lifestyle.Singleton); container.Register <IFontFamilyManager, FontFamilyManager>(SimpleInjector.Lifestyle.Singleton); }
public ShowStorageAdapter(ShowStorageAdapterSettings settings) { _container = new SimpleInjectorContainer(); _container.Register <CosmosClient>(() => new CosmosClient(settings.AccountEndpoint, settings.AccountKey)); _container.Register <IShowStore, ShowStoreCosmosDb>(); }
protected void Page_Load(object sender, EventArgs e) { var login = Session["Login"]; if (login == null) { Response.Redirect("~/login.aspx"); } var container = new SimpleInjector.Container(); Infra.CrossCutting.IoC.BootStrapper.RegisterServices(container); container.GetInstance <Imagem_ItapeviContext>().ChangeConnection(ConfigurationManager.ConnectionStrings["PgProdutos"].ToString()); var service = container.GetInstance <ICadastroAppService>(); var user = service.RetornaUsuario(Session["Login"].ToString()); if (!user.Modulos.Any(x => x.id_modulo == 2)) { Response.Redirect("~/AcessoNegado.aspx"); } var usuarios = service.ListaUsuarios(); GridUsuarios.DataSource = usuarios; GridUsuarios.DataBind(); }
/// <summary> /// Registers the view models. /// </summary> /// <param name="container">The container.</param> private void RegisterViewModels(Container container) { container.RegisterLocalization <MainWindowViewModel>(); container.RegisterLocalization <ThemeControlViewModel>(); container.RegisterLocalization <LanguageControlViewModel>(); container.RegisterLocalization <MainControlViewModel>(); container.RegisterLocalization <GameControlViewModel>(); container.RegisterLocalization <InstalledModsControlViewModel>(); container.RegisterLocalization <SortOrderControlViewModel>(); container.RegisterLocalization <ModHolderControlViewModel>(); container.RegisterLocalization <SearchModsControlViewModel>(); container.RegisterLocalization <CollectionModsControlViewModel>(); container.RegisterLocalization <AddNewCollectionControlViewModel>(); container.RegisterLocalization <ExportModCollectionControlViewModel>(); container.RegisterLocalization <MainConflictSolverControlViewModel>(); container.RegisterLocalization <MergeViewerControlViewModel>(); container.RegisterLocalization <ModCompareSelectorControlViewModel>(); container.RegisterLocalization <MergeViewerBinaryControlViewModel>(); container.RegisterLocalization <ModConflictIgnoreControlViewModel>(); container.RegisterLocalization <ModifyCollectionControlViewModel>(); container.RegisterLocalization <OptionsControlViewModel>(); container.RegisterLocalization <ConflictSolverModFilterControlViewModel>(); container.RegisterLocalization <ConflictSolverResetConflictsControlViewModel>(); container.RegisterLocalization <ConflictSolverDBSearchControlViewModel>(); container.RegisterLocalization <ConflictSolverCustomConflictsControlViewModel>(); container.RegisterLocalization <ShortcutsControlViewModel>(); container.RegisterLocalization <ModHashReportControlViewModel>(); }
public void SimpleInjector() { var container = new SimpleInjector.Container(); foreach (var type in _types) { container.Register(type, type); } int length = 0; if (Scenario == ResolveScenario.ResolveOne) { length = 1; } else if (Scenario == ResolveScenario.ResolveHalf) { length = _types.Length / 2; } else if (Scenario == ResolveScenario.ResolveAll) { length = _types.Length; } for (var i = 0; i < length; i++) { container.GetInstance(_types[i]); } container.Dispose(); }
protected void Page_Load(object sender, EventArgs e) { var login = Session["Login"]; if (login == null) { Response.Redirect("~/login.aspx"); } var container = new SimpleInjector.Container(); Infra.CrossCutting.IoC.BootStrapper.RegisterServices(container); container.GetInstance <Imagem_ItapeviContext>().ChangeConnection(ConfigurationManager.ConnectionStrings["PgProdutos"].ToString()); var service = container.GetInstance <ICadastroAppService>(); var user = service.RetornaUsuario(Session["Login"].ToString()); if (!user.Modulos.Any(x => x.id_modulo == 1)) { Response.Redirect("~/AcessoNegado.aspx"); } var categorias = service.ListaCategorias(); GridCategorias.DataSource = categorias; GridCategorias.DataBind(); if (ddlArmazenaImagens.Items.Count == 0) { ddlArmazenaImagens.Items.Add(new ListItem("Todos", "0")); ddlArmazenaImagens.Items.Add(new ListItem("Sim", "1")); ddlArmazenaImagens.Items.Add(new ListItem("Não", "2")); } }
public static void Initialize(SimpleInjector.Container container) { DbInitializer.container = container; context = container.GetInstance <WebLogContext>(); InitializeUser(); }
public static void RegisterTypes(SimpleInjector.Container container, string database) { container.Register <DialogEngine>(); container.RegisterInstance <IServiceProvider>(container); container.RegisterSingleton <IApiAiAppServiceFactory, ApiAiAppServiceFactory>(); container.RegisterSingleton <IHttpClientFactory, HttpClientFactory>(); container.RegisterSingleton <ISolicitud, SolicitudManager>(); container.RegisterSingleton <IIntencion, IntencionManager>(); container.RegisterSingleton <ISesion, SesionManager>(); container.RegisterSingleton <IChatLog, ChatLogManager>(); container.RegisterSingleton <ICurso, CursoManager>(); container.RegisterSingleton <IActividad, ActividadManager>(); if (database.Equals("ORACLE")) { container.Register <ISesionData, Upecito.Data.Oracle.Implementacion.SesionData>(); container.Register <ISolicitudData, Upecito.Data.Oracle.Implementacion.SolicitudData>(); container.Register <IIntencionData, Upecito.Data.Oracle.Implementacion.IntencionData>(); } if (database.Equals("MSSQLSERVER")) { container.Register <ISesionData, Upecito.Data.MSSQLSERVER.Implementacion.SesionData>(); container.Register <ISolicitudData, Upecito.Data.MSSQLSERVER.Implementacion.SolicitudData>(); container.Register <IIntencionData, Upecito.Data.MSSQLSERVER.Implementacion.IntencionData>(); container.Register <IChatLogData, Upecito.Data.MSSQLSERVER.Implementacion.ChatLogData>(); container.Register <ICursoData, Upecito.Data.MSSQLSERVER.Implementacion.CursoData>(); container.Register <IActividadData, Upecito.Data.MSSQLSERVER.Implementacion.ActividadData>(); } }
static void Main(string[] args) { var builder = new ConfigurationBuilder(); builder.SetBasePath(Directory.GetCurrentDirectory()) .AddXmlFile("App.config", optional: true, reloadOnChange: true) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true); builder.AddEnvironmentVariables(); Configuration = builder.Build(); var simple = new SimpleInjector.Container(); simple.AddOptions(Configuration); foreach (var v in Configuration.AsEnumerable()) { Console.WriteLine($"{v.Key} : {v.Value}"); } var dbOptions = simple.GetInstance <IOptions <DatabaseSettings> >(); Console.WriteLine($"DB Name : {dbOptions.Value.Name}"); Console.ReadKey(); }
private void btnStart_Click(object sender, EventArgs e) { if (this.btnStart.Text == "START") { var container = new SimpleInjector.Container(); container.Register <IChatServices, ChatServices>(); container.Register <IMessagesServices, MessagesServices>(); container.Register <IUsersByChatServices, UsersByChatServices>(); container.Register <IUsersServices, UsersServices>(); container.RegisterSingleton <PresenceContext>(); container.Verify(); //PresenceServiceInitializer.configure(container); this.btnStart.Text = "STOP"; } else { //PresenceServiceInitializer.getInstance().Stop(); this.btnStart.Text = "START"; } }
static void Main(string[] args) { string serviceName = typeof(Program).Assembly.GetName().Name; Console.Title = serviceName; Console.WriteLine($"{serviceName} running..."); #region Register Dependencies var container = new SimpleInjector.Container(); container.RegisterServices(); container.Verify(); #endregion var consumer = container.GetInstance <IConsumer <BariguiEvent> >(); var responseConsumer = container.GetInstance <IConsumer <BariguiEventResponse> >(); var bus = container.GetInstance <IEventBus>(); consumer.Consume(); responseConsumer.Consume(); Task.Run(() => { while (true) { bus.Publish(new BariguiEvent("Hello World!", serviceName)).Wait(); Thread.Sleep(5000); } }); Console.WriteLine("Listening for messages. Hit <return> to quit."); Console.ReadLine(); }
public MainForm(IConfigProvider configProvider, IWdcStoryContainer storyContainer, IStorySyncWorker syncWorker, SimpleInjector.Container diContainer, IStoryFileStore fileStore, IGuiContext guiContext ) { _configProvider = configProvider; _storyContainer = storyContainer; _diContainer = diContainer; _syncWorker = syncWorker; _fileStore = fileStore; _guiContext = guiContext; InitializeComponent(); // Set a few things up InitStoryList(); RefreshStoryList(); UpdateStatusMessage(_syncWorker.GetCurrentStatus().Message); // Subscribe to some events LogManager.OnLogEvent += new EventHandler <LogEventArgs>(OnLogEvent); _storyContainer.OnUpdate += new EventHandler <WdcStoryContainerEventArgs>(OnStoryContainerUpdate); _syncWorker.OnWorkerStatusChange += new EventHandler <StorySyncWorkerStatusEventArgs>(OnSyncWorkerStatusEvent); _syncWorker.OnStoryStatusChange += new EventHandler <StorySyncWorkerStoryStatusEventArgs>(OnSyncWorkerStoryStatusEvent); CheckInitialSetupRequired(); }
public MainWindow() { var container = new Container(); container.Register <IConfigService, ConfigService>(); container.Register <IScreenColorService, ScreenColorService>(); container.Register <IMonitorService, MonitorService>(); container.Verify(); _configService = container.GetInstance <IConfigService>(); _temperatureService = container.GetInstance <IScreenColorService>(); _monitorService = container.GetInstance <IMonitorService>(); Monitors = new ObservableCollection <Monitor>(_monitorService.GetMonitors()); SelectedMonitor = Monitors.FirstOrDefault(); bool exists = Process.GetProcessesByName(Path.GetFileNameWithoutExtension(Assembly.GetEntryAssembly().Location)).Length > 1; if (exists) //If this program already has an instance { try { NamedPipeClientStream pipeStream = new NamedPipeClientStream(".", "instance", PipeDirection.Out, PipeOptions.None); pipeStream.Connect(); Environment.Exit(0); } catch (TimeoutException oEx) { Debug.WriteLine(oEx.Message); } } else //If the program is not already running { _pipeServer = new NamedPipeServerStream("instance", PipeDirection.In, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous); _pipeServer.BeginWaitForConnection(WaitForConnectionCallBack, _pipeServer); } AssignKeyToConfigCommand = new RelayCommand(AssignKeyToConfig); SaveConfigCommand = new RelayCommand(SaveConfig); DeleteConfigCommand = new RelayCommand(DeleteConfig); MoveConfigUpCommand = new RelayCommand(MoveConfigUp); MoveConfigDownCommand = new RelayCommand(MoveConfigDown); RefreshMonitorsCommand = new RelayCommand(RefreshMonitors); _notifyIcon.Icon = Properties.Resources.icon; _notifyIcon.Click += NotifyIconOnClick; _notifyIcon.Visible = true; SystemEvents.SessionSwitch += SystemEventsOnSessionSwitch; SystemEvents.UserPreferenceChanging += SystemEvents_UserPreferenceChanging; SystemEvents.PaletteChanged += SystemEvents_PaletteChanged; SystemEvents.DisplaySettingsChanged += SystemEvents_DisplaySettingsChanged; InitializeComponent(); }
public void Run() { Container = new SimpleInjector.Container(); System.AppDomain.CurrentDomain.UnhandledException += CurrentDomainOnUnhandledException; ConfigureContainer(); InitializeMappings(); RunInitializers(); }
private SimpleInjector.Container GetContainer() { var container = new SimpleInjector.Container(); container.Collection.Register(typeof(IEventHandler <>), this.GetType().Assembly); return(container); }
public static void Initialize() { EnsureFolderSetup(); Logger.InitializeLogging(Path.Combine(ModsDirectory, "PPModLoader.log")); SimpleInjector.Container container = CompositionRoot.GetContainer(); _modManager = new ModManager(ModsDirectory, new JsonConfigProvider(), new FileSystemModLoader(), container); _modManager.Initialize(); }
public CadUsuario() { var container = new SimpleInjector.Container(); Infra.CrossCutting.IoC.BootStrapper.RegisterServices(container); container.GetInstance <Imagem_ItapeviContext>().ChangeConnection(ConfigurationManager.ConnectionStrings["PgProdutos"].ToString()); service = container.GetInstance <ICadastroAppService>(); }
static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); var di = new SimpleInjector.Container(); di.GetInstance<App>(); }
public ControllerTestHarness() { _container = new SimpleInjector.Container(); _container.RegisterSingleton<IApplicationSettings>(new Mock<IApplicationSettings>().Object); _container.RegisterSingleton<IContactService>(new Mock<IContactService>().Object); _container.RegisterSingleton<IInteractionService>(new Mock<IInteractionService>().Object); _fixture = new Fixture(); }
/// <summary> /// Sets up the configuration based on arguments passed in, config file, and environment /// </summary> /// <param name="args">The arguments.</param> /// <param name="config">The configuration.</param> /// <param name="container">The container.</param> /// <param name="license">The license.</param> /// <param name="notifyWarnLoggingAction">Notify warn logging action</param> public static void set_up_configuration(IList<string> args, ChocolateyConfiguration config, Container container, ChocolateyLicense license, Action<string> notifyWarnLoggingAction) { var fileSystem = container.GetInstance<IFileSystem>(); var xmlService = container.GetInstance<IXmlService>(); set_file_configuration(config, fileSystem, xmlService, notifyWarnLoggingAction); ConfigurationOptions.reset_options(); set_global_options(args, config, container); set_environment_options(config); set_license_options(config, license); set_environment_variables(config); }
public static void Bootstrap(HttpConfiguration config) { var container = new SimpleInjector.Container(); container.Register<IReportRepository<SummaryReport>>( ()=> new ReportRepository<SummaryReport>(), SimpleInjector.Lifestyle.Transient); container.Register<ISummaryReport>(() => new SummaryReport(container.GetInstance<IReportRepository<SummaryReport>>()), SimpleInjector.Lifestyle.Transient); container.RegisterDecorator(typeof(ISummaryReport), typeof(SummaryLogDecorator)); container.Verify(); config.DependencyResolver = new SimpleInjectorWebApiDependencyResolver(container); }
/// <summary> /// Sets up the configuration based on arguments passed in, config file, and environment /// </summary> /// <param name="args">The arguments.</param> /// <param name="config">The configuration.</param> /// <param name="container">The container.</param> /// <param name="license">The license.</param> /// <param name="notifyWarnLoggingAction">Notify warn logging action</param> public static void set_up_configuration(IList<string> args, ChocolateyConfiguration config, Container container, ChocolateyLicense license, Action<string> notifyWarnLoggingAction) { var fileSystem = container.GetInstance<IFileSystem>(); var xmlService = container.GetInstance<IXmlService>(); var configFileSettings = get_config_file_settings(fileSystem, xmlService); // must be done prior to setting the file configuration add_or_remove_licensed_source(license, configFileSettings); set_file_configuration(config, configFileSettings, fileSystem, notifyWarnLoggingAction); ConfigurationOptions.reset_options(); set_global_options(args, config, container); set_environment_options(config); set_environment_variables(config); // must be done last for overrides set_licensed_options(config, license, configFileSettings); // save all changes if there are any set_config_file_settings(configFileSettings, xmlService); }
private static SimpleInjector.Container InitCore(IEnumerable<Action<SimpleInjector.Container>> additionalRegistrations = null) { SimpleInjector.Container container = new SimpleInjector.Container(); InitCrossCutting(container); InitDAL(container); if (additionalRegistrations != null) { container.Options.AllowOverridingRegistrations = true; foreach (var additionalRegistration in additionalRegistrations) { additionalRegistration(container); } } container.Verify(); return container; }
private static void set_global_options(IList<string> args, ChocolateyConfiguration config, Container container) { ConfigurationOptions.parse_arguments_and_update_configuration( args, config, (option_set) => { option_set .Add("d|debug", "Debug - Run in Debug Mode.", option => config.Debug = option != null) .Add("v|verbose", "Verbose - See verbose messaging.", option => config.Verbose = option != null) .Add("acceptlicense|accept-license", "AcceptLicense - Accept license dialogs automatically.", option => config.AcceptLicense = option != null) .Add("y|yes|confirm", "Confirm all prompts - Chooses affirmative answer instead of prompting. Implies --accept-license", option => { config.PromptForConfirmation = option == null; config.AcceptLicense = option != null; }) .Add("f|force", "Force - force the behavior", option => config.Force = option != null) .Add("noop|whatif|what-if", "NoOp - Don't actually do anything.", option => config.Noop = option != null) .Add("r|limitoutput|limit-output", "LimitOutput - Limit the output to essential information", option => config.RegularOutput = option == null) .Add("execution-timeout=", "CommandExecutionTimeoutSeconds - Override the default execution timeout in the configuration of {0} seconds.".format_with(config.CommandExecutionTimeoutSeconds.to_string()), option => config.CommandExecutionTimeoutSeconds = int.Parse(option.remove_surrounding_quotes())) .Add("c=|cache=|cachelocation=|cache-location=", "CacheLocation - Location for download cache, defaults to %TEMP% or value in chocolatey.config file.", option => config.CacheLocation = option.remove_surrounding_quotes()) .Add("allowunofficial|allow-unofficial|allowunofficialbuild|allow-unofficial-build", "AllowUnofficialBuild - When not using the official build you must set this flag for choco to continue.", option => config.AllowUnofficialBuild = option != null) .Add("failstderr|failonstderr|fail-on-stderr|fail-on-standard-error|fail-on-error-output", "FailOnStandardError - Fail on standard error output (stderr), typically received when running external commands during install providers. This overrides the feature failOnStandardError.", option => config.Features.FailOnStandardError = option != null) .Add("use-system-powershell", "UseSystemPowerShell - Execute PowerShell using an external process instead of the built-in PowerShell host.", option => config.Features.UsePowerShellHost = option == null) ; }, (unparsedArgs) => { if (!string.IsNullOrWhiteSpace(config.CommandName)) { // save help for next menu config.HelpRequested = false; } }, () => { }, () => { var commandsLog = new StringBuilder(); IEnumerable<ICommand> commands = container.GetAllInstances<ICommand>(); foreach (var command in commands.or_empty_list_if_null()) { var attributes = command.GetType().GetCustomAttributes(typeof(CommandForAttribute), false).Cast<CommandForAttribute>(); foreach (var attribute in attributes.or_empty_list_if_null()) { commandsLog.AppendFormat(" * {0} - {1}\n", attribute.CommandName, attribute.Description); } } "chocolatey".Log().Info(@"This is a listing of all of the different things you can pass to choco. "); "chocolatey".Log().Info(ChocolateyLoggers.Important, "Commands"); "chocolatey".Log().Info(@" {0} Please run chocolatey with `choco command -help` for specific help on each command. ".format_with(commandsLog.ToString())); "chocolatey".Log().Info(ChocolateyLoggers.Important, @"How To Pass Options / Switches"); "chocolatey".Log().Info(@" You can pass options and switches in the following ways: * `-`, `/`, or `--` (one character switches should not use `--`) * **Option Bundling / Bundled Options**: One character switches can be bundled. e.g. `-d` (debug), `-f` (force), `-v` (verbose), and `-y` (confirm yes) can be bundled as `-dfvy`. * ***Note:*** If `debug` or `verbose` are bundled with local options (not the global ones above), some logging may not show up until after the local options are parsed. * **Use Equals**: You can also include or not include an equals sign `=` between options and values. * **Quote Values**: When you need to quote things, such as when using spaces, please use apostrophes (`'value'`). In cmd.exe you may be able to use just double quotes (`""value""`) but in powershell.exe you may need to either escape the quotes with backticks (`` `""value`"" ``) or use a combination of double quotes and apostrophes (`""'value'""`). This is due to the hand off to PowerShell - it seems to strip off the outer set of quotes. * Options and switches apply to all items passed, so if you are installing multiple packages, and you use `--version=1.0.0`, choco is going to look for and try to install version 1.0.0 of every package passed. So please split out multiple package calls when wanting to pass specific options. "); "chocolatey".Log().Info(ChocolateyLoggers.Important, "Default Options and Switches"); }); }
private static void OnStartup(string[] args) { // TODO free console for UI execution // Bootstrap container container = new SimpleInjector.Container(); container.RegisterSingleton<IPlatformFacade, WindowsPlatform>(); container.RegisterSingleton<IWindowManagerService, WindowManagerService>(); container.RegisterSingleton<IKeyMapService, KeyMapService>(); container.RegisterSingleton<INotificationService, NotificationService>(); container.RegisterSingleton<IMainWindow, MainWindow>(); // Register default command set var commands = AppDomain.CurrentDomain.GetAssemblies() .SelectMany(s => s.GetTypes()) .Where(p => p != typeof(ICommand) && typeof(ICommand).IsAssignableFrom(p)) .ToList(); container.RegisterCollection<ICommand>(commands); container.Register( typeof(ICommandHandler<>), container.GetTypesToRegister(typeof(ICommandHandler<>), new[] { Assembly.GetExecutingAssembly() }) .Where(t => t.IsPublic)); // Register handlers var commandHandlers = commands.Select(command => container.GetInstance(typeof(ICommandHandler<>).MakeGenericType(command))); container.RegisterSingleton<ICommandService>( () => new CommandService(container.GetAllInstances<ICommand>(), commandHandlers)); container.Verify(); mainForm = container.GetInstance<IMainWindow>() as Form; // Parse arguments and run the app var getopt = new GetOpt(Options); char returnChar = ' '; int optionIndex = 0; string optionArg = null; bool startWindowManager = true; try { do { // parse the args switch (returnChar) { case 'h': Console.Write(getopt.Description); return; case 'v': Console.WriteLine(Application.ProductVersion); return; case 'f': // parse alternate rc file configFile = optionArg; break; case 'c': // send a command startWindowManager = false; break; case 'r': // reset all windows to decorated regular state, in case things screw up :( startWindowManager = false; WindowManagerService.Reset(); break; } returnChar = getopt.Parse(args, ref optionIndex, out optionArg); } while (returnChar != ' '); } catch (GetOpt.InvalidOptionException e) { Console.WriteLine(Properties.Resources.Option_Help_Error); Console.WriteLine(e); return; } if (startWindowManager) { // Start the services ((ServiceBase)container.GetInstance<IKeyMapService>()).Start(); ((ServiceBase)container.GetInstance<IWindowManagerService>()).Start(); ((ServiceBase)container.GetInstance<INotificationService>()).Start(); // set the internal variables // set the data structures // read rc file ////CommandManager.Execute((int)CommandManager.OtherCommands.source, new string[] { _configFile }); var keyMapService = container.GetInstance<IKeyMapService>(); // Top keymap does not require the window on focus, they are global hot keys // Prefix key must reside here keyMapService.AddKeyMap("top"); keyMapService.SetTopKey("top", Keys.Control | Keys.B); // Root keymap is the default keymap invoked via Prefix key with readkey command // All other default shortcuts reside here keyMapService.AddKeyMap("root"); var commandService = container.GetInstance<ICommandService>(); commandService.Run("definekey top T readkey root"); // Set default variables // commandService.Run() ////keyMapService.SetTopKey("root", Keys.Control | Keys.T); Application.Run(mainForm); } else { // check if an instance already runs // send the commands // throw output to console or to the bar } }
public BaseTest() { this.Container = IoCBootstrapper.GetContainer(); }
private static void set_hash_provider(ChocolateyConfiguration config, Container container) { if (!config.Features.UseFipsCompliantChecksums) { var hashprovider = container.GetInstance<IHashProvider>(); try { hashprovider.set_hash_algorithm(CryptoHashProviderType.Md5); } catch (Exception ex) { if (!config.CommandName.is_equal_to("feature")) { if (ex.InnerException != null && ex.InnerException.Message.contains("FIPS")) { "chocolatey".Log().Warn(ChocolateyLoggers.Important, @" FIPS Mode detected - run 'choco feature enable -n {0}' to use Chocolatey.".format_with(ApplicationParameters.Features.UseFipsCompliantChecksums)); throw new ApplicationException("When FIPS Mode is enabled, Chocolatey requires {0} feature also be enabled.".format_with(ApplicationParameters.Features.UseFipsCompliantChecksums)); } throw; } } } }
private static void set_global_options(IList<string> args, ChocolateyConfiguration config, Container container) { ConfigurationOptions.parse_arguments_and_update_configuration( args, config, (option_set) => { option_set .Add("d|debug", "Debug - Show debug messaging.", option => config.Debug = option != null) .Add("v|verbose", "Verbose - Show verbose messaging.", option => config.Verbose = option != null) .Add("acceptlicense|accept-license", "AcceptLicense - Accept license dialogs automatically. Reserved for future use.", option => config.AcceptLicense = option != null) .Add("y|yes|confirm", "Confirm all prompts - Chooses affirmative answer instead of prompting. Implies --accept-license", option => { config.PromptForConfirmation = option == null; config.AcceptLicense = option != null; }) .Add("f|force", "Force - force the behavior. Do not use force during normal operation - it subverts some of the smart behavior for commands.", option => config.Force = option != null) .Add("noop|whatif|what-if", "NoOp / WhatIf - Don't actually do anything.", option => config.Noop = option != null) .Add("r|limitoutput|limit-output", "LimitOutput - Limit the output to essential information", option => config.RegularOutput = option == null) .Add("timeout=|execution-timeout=", "CommandExecutionTimeout (in seconds) - The time to allow a command to finish before timing out. Overrides the default execution timeout in the configuration of {0} seconds.".format_with(config.CommandExecutionTimeoutSeconds.to_string()), option => { int timeout = 0; int.TryParse(option.remove_surrounding_quotes(), out timeout); if (timeout > 0) { config.CommandExecutionTimeoutSeconds = timeout; } }) .Add("c=|cache=|cachelocation=|cache-location=", "CacheLocation - Location for download cache, defaults to %TEMP% or value in chocolatey.config file.", option => config.CacheLocation = option.remove_surrounding_quotes()) .Add("allowunofficial|allow-unofficial|allowunofficialbuild|allow-unofficial-build", "AllowUnofficialBuild - When not using the official build you must set this flag for choco to continue.", option => config.AllowUnofficialBuild = option != null) .Add("failstderr|failonstderr|fail-on-stderr|fail-on-standard-error|fail-on-error-output", "FailOnStandardError - Fail on standard error output (stderr), typically received when running external commands during install providers. This overrides the feature failOnStandardError.", option => config.Features.FailOnStandardError = option != null) .Add("use-system-powershell", "UseSystemPowerShell - Execute PowerShell using an external process instead of the built-in PowerShell host. Should only be used when internal host is failing. Available in 0.9.10+.", option => config.Features.UsePowerShellHost = option == null) ; }, (unparsedArgs) => { if (!string.IsNullOrWhiteSpace(config.CommandName)) { // save help for next menu config.HelpRequested = false; } }, () => { }, () => { var commandsLog = new StringBuilder(); IEnumerable<ICommand> commands = container.GetAllInstances<ICommand>(); foreach (var command in commands.or_empty_list_if_null()) { var attributes = command.GetType().GetCustomAttributes(typeof(CommandForAttribute), false).Cast<CommandForAttribute>(); foreach (var attribute in attributes.or_empty_list_if_null()) { commandsLog.AppendFormat(" * {0} - {1}\n", attribute.CommandName, attribute.Description); } } "chocolatey".Log().Info(@"This is a listing of all of the different things you can pass to choco. "); "chocolatey".Log().Info(ChocolateyLoggers.Important, "Commands"); "chocolatey".Log().Info(@" {0} Please run chocolatey with `choco command -help` for specific help on each command. ".format_with(commandsLog.ToString())); "chocolatey".Log().Info(ChocolateyLoggers.Important, @"How To Pass Options / Switches"); "chocolatey".Log().Info(@" You can pass options and switches in the following ways: * Unless stated otherwise, an option/switch should only be passed one time. Otherwise you may find weird/non-supported behavior. * `-`, `/`, or `--` (one character switches should not use `--`) * **Option Bundling / Bundled Options**: One character switches can be bundled. e.g. `-d` (debug), `-f` (force), `-v` (verbose), and `-y` (confirm yes) can be bundled as `-dfvy`. * NOTE: If `debug` or `verbose` are bundled with local options (not the global ones above), some logging may not show up until after the local options are parsed. * **Use Equals**: You can also include or not include an equals sign `=` between options and values. * **Quote Values**: When you need to quote an entire argument, such as when using spaces, please use a combination of double quotes and apostrophes (`""'value'""`). In cmd.exe you can just use double quotes (`""value""`) but in powershell.exe you should use backticks (`` `""value`"" ``) or apostrophes (`'value'`). Using the combination allows for both shells to work without issue, except for when the next section applies. * **Pass quotes in arguments**: When you need to pass quoted values to to something like a native installer, you are in for a world of fun. In cmd.exe you must pass it like this: `-ia ""/yo=""""Spaces spaces""""""`. In PowerShell.exe, you must pass it like this: `-ia '/yo=""""Spaces spaces""""'`. No other combination will work. In PowerShell.exe if you are on version v3+, you can try `--%` before `-ia` to just pass the args through as is, which means it should not require any special workarounds. * Options and switches apply to all items passed, so if you are installing multiple packages, and you use `--version=1.0.0`, choco is going to look for and try to install version 1.0.0 of every package passed. So please split out multiple package calls when wanting to pass specific options. "); "chocolatey".Log().Info(ChocolateyLoggers.Important, "Default Options and Switches"); }); }