public ConnectionController(IContainer c) { model = c.Resolve <Model>(); mserver = c.Resolve <MulticastServerService>(); peerFinder = c.Resolve <LANPeerFinderService>(); setupLocalNetwork(); }
public ConnectionController(IContainer c) { model = c.Resolve<Model>(); mserver = c.Resolve<MulticastServerService>(); peerFinder = c.Resolve<LANPeerFinderService>(); setupLocalNetwork(); }
public App() { _mainViewModels = new List <MainViewModel>(); InitializeComponent(); var builder = new ContainerBuilder(); builder.RegisterType <SettingsService>().As <ISettingsService>().SingleInstance(); builder.RegisterType <DefaultValueProvider>().As <IDefaultValueProvider>().SingleInstance(); builder.RegisterType <TrayProcessCommunicationService>().As <ITrayProcessCommunicationService>().SingleInstance(); builder.RegisterType <DialogService>().As <IDialogService>().SingleInstance(); builder.RegisterType <KeyboardCommandService>().As <IKeyboardCommandService>().InstancePerDependency(); builder.RegisterType <MainViewModel>().InstancePerDependency(); builder.RegisterType <SettingsViewModel>().InstancePerDependency(); _container = builder.Build(); _settingsService = _container.Resolve <ISettingsService>(); _settingsService.ApplicationSettingsChanged += OnApplicationSettingsChanged; _trayProcessCommunicationService = _container.Resolve <ITrayProcessCommunicationService>(); _applicationSettings = _settingsService.GetApplicationSettings(); }
protected override async void OnLaunched(LaunchActivatedEventArgs args) { if (!_alreadyLaunched) { var logDirectory = await ApplicationData.Current.LocalCacheFolder.CreateFolderAsync("Logs", CreationCollisionOption.OpenIfExists); var logFile = Path.Combine(logDirectory.Path, "fluentterminal.app.log"); var configFile = await logDirectory.CreateFileAsync("config.json", CreationCollisionOption.OpenIfExists); var configContent = await FileIO.ReadTextAsync(configFile); if (string.IsNullOrWhiteSpace(configContent)) { configContent = JsonConvert.SerializeObject(new Logger.Configuration()); await FileIO.WriteTextAsync(configFile, configContent); } var config = JsonConvert.DeserializeObject <Logger.Configuration>(configContent) ?? new Logger.Configuration(); Logger.Instance.Initialize(logFile, config); var viewModel = _container.Resolve <MainViewModel>(); viewModel.AddTerminal(); await CreateMainView(typeof(MainPage), viewModel, true).ConfigureAwait(true); Window.Current.Activate(); } else if (_mainViewModels.Count == 0) { await CreateSecondaryView <MainViewModel>(typeof(MainPage), true).ConfigureAwait(true); } }
protected override async void OnLaunched(LaunchActivatedEventArgs args) { if (!_alreadyLaunched) { await InitializeLogger(); Task.Run(async() => await JumpListHelper.Update(_settingsService.GetShellProfiles())); var viewModel = _container.Resolve <MainViewModel>(); if (args.Arguments.StartsWith(JumpListHelper.ShellProfileFlag)) { viewModel.AddTerminal(Guid.Parse(args.Arguments.Replace(JumpListHelper.ShellProfileFlag, string.Empty))); } else { viewModel.AddTerminal(); } await CreateMainView(typeof(MainPage), viewModel, true).ConfigureAwait(true); Window.Current.Activate(); } else if (_mainViewModels.Count == 0) { await CreateSecondaryView <MainViewModel>(typeof(MainPage), true).ConfigureAwait(true); } else if (args.Arguments.StartsWith(JumpListHelper.ShellProfileFlag)) { var location = _applicationSettings.NewTerminalLocation; var profile = _settingsService.GetShellProfile(Guid.Parse(args.Arguments.Replace(JumpListHelper.ShellProfileFlag, string.Empty))); await CreateTerminal(profile, location).ConfigureAwait(true); } }
public MainWindow() { GroupAddressesProvider.SeedList(); Container = BuildContainer(); mesh = Container.Resolve <IBluetoothMeshContext>(); foreach (var server in mesh.NodeServers) { server.SetDispacher(Container.Resolve <ICommandDispatcher>()); } Node clientNode = mesh.Nodes[0]; bearer = mesh.NodeServers.ToList().FirstOrDefault(x => x.Node.Id == 1); serverModel = (ConfigurationClientModel)clientNode.Elements[ElementType.primary].Models[ModelType.ConfigurationClient]; InitializeComponent(); Providers.LayoutProvider.DrawGrid(canvas); Providers.LayoutProvider.DrawGrid(canvas); Providers.LayoutProvider.DrawConnections(canvas, mesh); Providers.LayoutProvider.DrawNodes(canvas, mesh); Providers.LayoutProvider.ColorNodes(); Providers.LayoutProvider.SignNodes(canvas, mesh); Setup(); }
public App() { _mainViewModels = new List <MainViewModel>(); InitializeComponent(); UnhandledException += OnUnhandledException; var applicationDataContainers = new ApplicationDataContainers { LocalSettings = new ApplicationDataContainerAdapter(ApplicationData.Current.LocalSettings), RoamingSettings = new ApplicationDataContainerAdapter(ApplicationData.Current.RoamingSettings), KeyBindings = new ApplicationDataContainerAdapter(ApplicationData.Current.RoamingSettings.CreateContainer(Constants.KeyBindingsContainerName, ApplicationDataCreateDisposition.Always)), ShellProfiles = new ApplicationDataContainerAdapter(ApplicationData.Current.LocalSettings.CreateContainer(Constants.ShellProfilesContainerName, ApplicationDataCreateDisposition.Always)), Themes = new ApplicationDataContainerAdapter(ApplicationData.Current.RoamingSettings.CreateContainer(Constants.ThemesContainerName, ApplicationDataCreateDisposition.Always)) }; var builder = new ContainerBuilder(); builder.RegisterType <SettingsService>().As <ISettingsService>().SingleInstance(); builder.RegisterType <DefaultValueProvider>().As <IDefaultValueProvider>().SingleInstance(); builder.RegisterType <TrayProcessCommunicationService>().As <ITrayProcessCommunicationService>().SingleInstance(); builder.RegisterType <DialogService>().As <IDialogService>().SingleInstance(); builder.RegisterType <KeyboardCommandService>().As <IKeyboardCommandService>().InstancePerDependency(); builder.RegisterType <NotificationService>().As <INotificationService>().InstancePerDependency(); builder.RegisterType <UpdateService>().As <IUpdateService>().InstancePerDependency(); builder.RegisterType <MainViewModel>().InstancePerDependency(); builder.RegisterType <SettingsViewModel>().InstancePerDependency(); builder.RegisterType <ThemeParserFactory>().As <IThemeParserFactory>().SingleInstance(); builder.RegisterType <ITermThemeParser>().As <IThemeParser>().SingleInstance(); builder.RegisterType <FluentTerminalThemeParser>().As <IThemeParser>().SingleInstance(); builder.RegisterType <ClipboardService>().As <IClipboardService>().SingleInstance(); builder.RegisterType <FileSystemService>().As <IFileSystemService>().SingleInstance(); builder.RegisterType <SystemFontService>().As <ISystemFontService>().SingleInstance(); builder.RegisterType <ShellProfileSelectionDialog>().As <IShellProfileSelectionDialog>().InstancePerDependency(); builder.RegisterType <CreateKeyBindingDialog>().As <ICreateKeyBindingDialog>().InstancePerDependency(); builder.RegisterType <InputDialog>().As <IInputDialog>().InstancePerDependency(); builder.RegisterType <MessageDialogAdapter>().As <IMessageDialog>().InstancePerDependency(); builder.RegisterType <ApplicationViewAdapter>().As <IApplicationView>().InstancePerDependency(); builder.RegisterType <DispatcherTimerAdapter>().As <IDispatcherTimer>().InstancePerDependency(); builder.RegisterType <StartupTaskService>().As <IStartupTaskService>().SingleInstance(); builder.RegisterInstance(applicationDataContainers); _container = builder.Build(); _settingsService = _container.Resolve <ISettingsService>(); _settingsService.ApplicationSettingsChanged += OnApplicationSettingsChanged; _trayProcessCommunicationService = _container.Resolve <ITrayProcessCommunicationService>(); _applicationSettings = _settingsService.GetApplicationSettings(); _commandLineParser = new Parser(settings => { settings.CaseSensitive = false; settings.CaseInsensitiveEnumValues = true; }); }
public async Task Subscriber_ProcessTheMessageTheSecondTime_MessageMustBeRemovedFromTheRabbitMq() { //prepare IConfiguration configuration = ConfigurationHelper.ProvideConfiguration(); var exchangeName = "Subscriber_ProcessTheMessageTheSecondTime_MessageMustBeRemovedFromTheRabbitMq.exchangename"; configuration["rabbitmq:exchangename"] = exchangeName; configuration["rabbitmq:waitexchangename"] = exchangeName.Replace("exchangename", "waitexchangename"); configuration["rabbitmq:retryfactor"] = 100.ToString(); var maxretrycount = 2; IContainer container = ConfigurationHelper.ConfigureContainer(configuration); //create Subscriber var bookingCreatedSubscriberFactory = container.Resolve <ISubscriberFactory>(); ISubscriber typedSubscriber = await bookingCreatedSubscriberFactory .CreateSubscriberAsync("Subscriber_ProcessTheMessageTheSecondTime_MessageMustBeRemovedFromTheRabbitMq" + ".typedbookingcreatedconsumer", new List <string> { "*.entity.create.booking" }, maxretrycount); BookingTypedConsumer typedConsumer = new BookingTypedConsumer(1); typedSubscriber.Subscribe(SubscriptionBuilder.Create().AddDefaultSubscription(() => typedConsumer).Build()); //create Publisher var publisher = container.Resolve <IPublisher>(); string routingKey = "changetracker.entity.create.booking"; //act BookingCreated bookingCreated = new BookingCreated() { BookingName = string.Concat("Microsoft Sale", Guid.NewGuid().ToString()) }; var bookingCreatedIntegrationEvent = new IntegrationEvent <BookingCreated>() { Content = bookingCreated, EventType = "bookingcreated" }; await publisher.PublishEventAsync(bookingCreatedIntegrationEvent, routingKey); await Task.Delay(500); //check typedConsumer.ProcessedIntegrationEvent.ShouldBeEquivalentTo(bookingCreatedIntegrationEvent); typedConsumer.CountOfAttempts.Should().Be(2); container.Dispose(); }
public static TeltonikaServer ResolveTeltonicaListner() { Container = BuildContainer(); Container.Resolve <ReverseGeoCodingService>(); Container.Resolve <IBusControl>(); var listner = Container.Resolve <TeltonikaServer>(); return(listner); }
public ServiceRunner() { _components = new Container(); // Start log4net up XmlConfigurator.Configure(); GlobalContext.Properties["component"] = "Fourth.StarChef.MSMQ"; _globalUpdateTimeStamps = new Hashtable(); _activeTaskDatabaseIDs = new Hashtable(); var builder = new ContainerBuilder(); builder.RegisterModule <DependencyConfiguration>(); IContainer container = builder.Build(); _appConfiguration = container.Resolve <IAppConfiguration>(); _listener = container.Resolve <IListener>(); _listener.MessageNotProcessing += _listener_MessageNotProcessing; // Recommended in: https://docs.hangfire.io/en/latest/configuration/using-sql-server.html var configuration = GlobalConfiguration.Configuration .UseAutofacActivator(container) .UseSqlServerStorage("SL_login", new SqlServerStorageOptions { CommandBatchMaxTimeout = TimeSpan.FromMinutes(5), SlidingInvisibilityTimeout = TimeSpan.FromMinutes(5), QueuePollInterval = TimeSpan.Zero, UseRecommendedIsolationLevel = true, UsePageLocksOnDequeue = true, DisableGlobalLocks = true }) .UseLog4NetLogProvider(); if (Environment.UserInteractive) { configuration.UseColouredConsoleLogProvider(LogLevel.Debug); } GlobalJobFilters.Filters.Add(new AutomaticRetryAttribute { Attempts = 1, DelaysInSeconds = new[] { 60 }, OnAttemptsExceeded = AttemptsExceededAction.Fail, LogEvents = true }); _options = new BackgroundJobServerOptions { //WorkerCount = Environment.ProcessorCount * 5, WorkerCount = Environment.ProcessorCount, Queues = new string[] { JobQueue.Default.ToString().ToLower(), JobQueue.Critical.ToString().ToLower() } }; }
private void AutoFacBenchmark(IContainer container) { using (container.BeginLifetimeScope()) { Console.WriteLine(""); Console.WriteLine(""); Console.WriteLine("Continuing with AutoFac tests"); Stopwatch timer; TimeSpan elapsed5; timer = Stopwatch.StartNew(); for (int i = 0; i < Iterations; i++) { var instance = container.Resolve <ITestClass>(); } timer.Stop(); elapsed5 = timer.Elapsed; Singleton = new KeyValuePair <TimeSpan, TimeSpan>(Singleton.Key, elapsed5); Console.WriteLine("{0} instances created with singleton resolves in {1} ms", Iterations, elapsed5.TotalMilliseconds); timer = Stopwatch.StartNew(); for (int i = 0; i < Iterations; i++) { var instance = container.Resolve <ITestClass2>(); } timer.Stop(); elapsed5 = timer.Elapsed; Transient = new KeyValuePair <TimeSpan, TimeSpan>(Transient.Key, elapsed5); Console.WriteLine("{0} instances created with transient resolves in {1} ms", Iterations, elapsed5.TotalMilliseconds); timer = Stopwatch.StartNew(); for (int i = 0; i < Iterations; i++) { var instance = container.ResolveNamed <ITestClass>(ServiceName); } timer.Stop(); elapsed5 = timer.Elapsed; Console.WriteLine("{0} instances created with transient resolves by name {1} ms", Iterations, elapsed5.TotalMilliseconds); timer = Stopwatch.StartNew(); for (int i = 0; i < Iterations; i++) { var instance = container.Resolve <ITestClass3>(); if (instance.TClass == null) { Console.WriteLine("Injection failed"); } } timer.Stop(); elapsed5 = timer.Elapsed; TransientWithInjection = new KeyValuePair <TimeSpan, TimeSpan>(TransientWithInjection.Key, elapsed5); Console.WriteLine("{0} instances created with transient resolves with injection in {1} ms", Iterations, elapsed5.TotalMilliseconds); } }
//------------------------------------------------------------------------------------------------ // construction //------------------------------------------------------------------------------------------------ public DeribitService(DeribitConfig config) { // configuration this.deribitconfig = config; // logging this.logger = Serilog.Log.ForContext <DeribitService>(); // container var containerbuilder = new ContainerBuilder(); containerbuilder.RegisterModule(new DeribitModule(this)); this.container = containerbuilder.Build(); // core services this.WebSocket2 = container.Resolve <DeribitWebSocketService>(); this.JsonRpc2 = container.Resolve <DeribitJsonRpcService>(); // sub services this.Authentication2 = container.Resolve <DeribitAuthenticationService>(); this.AccountManagement2 = container.Resolve <DeribitAccountManagementService>(); this.SessionManagement2 = container.Resolve <DeribitSessionManagementService>(); this.Supporting2 = container.Resolve <DeribitSupportingService>(); this.SubscriptionManagement2 = container.Resolve <DeribitSubscriptionManagementService>(); this.Trading2 = container.Resolve <DeribitTradingService>(); this.MarketData2 = container.Resolve <DeribitMarketDataService>(); // connect if (config.ConnectOnConstruction) { this.Connect(default).Wait();
private void CreateGuestMember() { var _customerService = _appContainer.Resolve <IUserService>(); var ipAddress = HttpContext.Current.Request.UserHostAddress; if (!_customerService.EmailControl(ipAddress)) { _customerService.CreateGuestMember(ipAddress); FormsAuthentication.SetAuthCookie(ipAddress, true); } }
protected override object GetInstance(Type service, string key) { if (string.IsNullOrWhiteSpace(key)) { return(container.Resolve(service)); } else { return(container.ResolveNamed(key, service)); } }
public async Task CanCheckIfPullRequestsExist() { var sut = vContainer.Resolve <IGitHubUtilities>(); var errorsAndInfos = new ErrorsAndInfos(); var hasOpenPullRequest = await HasOpenPullRequestAsync(sut, "", errorsAndInfos); if (hasOpenPullRequest.Inconclusive) { return; } Assert.IsFalse(errorsAndInfos.AnyErrors(), errorsAndInfos.ErrorsPlusRelevantInfos()); Assert.IsTrue(hasOpenPullRequest.YesNo); hasOpenPullRequest = await HasOpenPullRequestAsync(sut, "1", errorsAndInfos); if (hasOpenPullRequest.Inconclusive) { return; } Assert.IsFalse(errorsAndInfos.AnyErrors(), errorsAndInfos.ErrorsPlusRelevantInfos()); Assert.IsFalse(hasOpenPullRequest.YesNo); hasOpenPullRequest = await HasOpenPullRequestForThisBranchAsync(sut, true, errorsAndInfos); if (hasOpenPullRequest.Inconclusive) { return; } Assert.IsFalse(errorsAndInfos.AnyErrors(), errorsAndInfos.ErrorsPlusRelevantInfos()); Assert.IsFalse(hasOpenPullRequest.YesNo); hasOpenPullRequest = await HasOpenPullRequestForThisBranchAsync(sut, false, errorsAndInfos); if (hasOpenPullRequest.Inconclusive) { return; } Assert.IsFalse(errorsAndInfos.AnyErrors(), errorsAndInfos.ErrorsPlusRelevantInfos()); Assert.IsTrue(hasOpenPullRequest.YesNo); var hasPullRequest = await HasPullRequestForThisBranchAndItsHeadTipAsync(sut, errorsAndInfos); if (hasOpenPullRequest.Inconclusive) { return; } Assert.IsFalse(errorsAndInfos.AnyErrors(), errorsAndInfos.ErrorsPlusRelevantInfos()); Assert.IsTrue(hasPullRequest.YesNo); }
public static IPropertyMatcher GetProvider(string agencyCode) { if (!container .Resolve <IEnumerable <PropertyMatcher> >().Any(o => o.AgencyCode.Equals(agencyCode, StringComparison.OrdinalIgnoreCase))) { return(null); } return(container .Resolve <IEnumerable <PropertyMatcher> >()? .FirstOrDefault(o => o.AgencyCode.Equals(agencyCode, StringComparison.OrdinalIgnoreCase))); }
public static void MakeCloud(IContainer container = null) { container ??= new ConsoleContainerConfigurator().Configure(); Of(() => container.Resolve <IWordReader>()) .Then(r => r.ReadWords()) .Then(words => container.Resolve <IStatisticProvider>().GetWordStatistics(words)) .Then(statistic => container.Resolve <IWordLayouter>().AddWords(statistic)) .Then(none => container.Resolve <ICloudRenderer>().RenderCloud()) .Then(path => Console.WriteLine($"Cloud saved in {path}")) .OnFail(Console.WriteLine); }
private void AutoFacBenchmark(IContainer container) { using (container.BeginLifetimeScope()) { Console.WriteLine(""); Console.WriteLine(""); Console.WriteLine("Continuing with AutoFac tests"); Stopwatch timer; TimeSpan elapsed5; timer = Stopwatch.StartNew(); for (int i = 0; i < Iterations; i++) { var instance = container.Resolve<ITestClass>(); } timer.Stop(); elapsed5 = timer.Elapsed; Singleton = new KeyValuePair<TimeSpan, TimeSpan>(Singleton.Key, elapsed5); Console.WriteLine("{0} instances created with singleton resolves in {1} ms", Iterations, elapsed5.TotalMilliseconds); timer = Stopwatch.StartNew(); for (int i = 0; i < Iterations; i++) { var instance = container.Resolve<ITestClass2>(); } timer.Stop(); elapsed5 = timer.Elapsed; Transient = new KeyValuePair<TimeSpan, TimeSpan>(Transient.Key, elapsed5); Console.WriteLine("{0} instances created with transient resolves in {1} ms", Iterations, elapsed5.TotalMilliseconds); timer = Stopwatch.StartNew(); for (int i = 0; i < Iterations; i++) { var instance = container.ResolveNamed<ITestClass>(ServiceName); } timer.Stop(); elapsed5 = timer.Elapsed; Console.WriteLine("{0} instances created with transient resolves by name {1} ms", Iterations, elapsed5.TotalMilliseconds); timer = Stopwatch.StartNew(); for (int i = 0; i < Iterations; i++) { var instance = container.Resolve<ITestClass3>(); if (instance.TClass == null) Console.WriteLine("Injection failed"); } timer.Stop(); elapsed5 = timer.Elapsed; TransientWithInjection = new KeyValuePair<TimeSpan, TimeSpan>(TransientWithInjection.Key, elapsed5); Console.WriteLine("{0} instances created with transient resolves with injection in {1} ms", Iterations, elapsed5.TotalMilliseconds); } }
/// <summary> /// Initializes a new instance of <see cref="CurveDisplay"/>. /// </summary> public CurveDisplay() { InitializeComponent(); _container = new ContainerFactory(this).Build(); _printingRedrawRequest = _container.Resolve<IPrintingRedrawRequest>(); TimeDoublePlottingSystem = _container.Resolve<TimeDoublePlottingSystem>(); _curveDrawingSurfaceControl = (FrameworkElement)_container.Resolve<ICurveDrawingSurface>(); SurfaceViewbox.Child = _curveDrawingSurfaceControl; }
public async Task Publisher_PublishDirectEventAsync_MessageMustBeSerializedAndCorrectlyRoutedToSpecificSubscriber() { //prepare IConfiguration configuration = ConfigurationHelper.ProvideConfiguration(); var exchangeName = "Publisher_PublishDirectEventAsync_MessageMustBeSerializedAndCorrectlyRoutedToSpecificSubscriber.exchangename"; configuration["rabbitmq:exchangename"] = exchangeName; configuration["rabbitmq:waitexchangename"] = exchangeName.Replace("exchangename", "waitexchangename"); var maxretrycount = 2; IContainer container = ConfigurationHelper.ConfigureContainer(configuration); //create Subscriber var bookingCreatedSubscriberFactory = container.Resolve <ISubscriberFactory>(); string subscriberName = "Publisher_PublishDirectEventAsync_MessageMustBeSerializedAndCorrectlyRoutedToSpecificSubscriber.typedbookingcreatedconsumer"; ISubscriber typedSubscriber = await bookingCreatedSubscriberFactory .CreateSubscriberAsync(subscriberName, (List <string>) null, maxretrycount); BookingTypedConsumer typedConsumer = new BookingTypedConsumer(0); typedSubscriber.Subscribe(SubscriptionBuilder.Create().AddDefaultSubscription(() => typedConsumer).Build()); //create Publisher var publisher = container.Resolve <IPublisher>(); //act BookingCreated bookingCreated = new BookingCreated() { BookingName = string.Concat("Microsoft Sale", Guid.NewGuid().ToString()) }; var bookingCreatedIntegrationEvent = new IntegrationEvent <BookingCreated>() { Content = bookingCreated, EventType = "bookingcreated" }; await publisher.PublishDirectEventAsync(bookingCreatedIntegrationEvent, subscriberName); await Task.Delay(200); //check typedConsumer.ProcessedIntegrationEvent.ShouldBeEquivalentTo(bookingCreatedIntegrationEvent); typedConsumer.CountOfAttempts.Should().Be(1); container.Dispose(); }
private void Parse() { database.DeleteAll(); ParserWorker parser = new ParserWorker(container.Resolve <IParser>(), container.Resolve <IParserSettings>(), database); parser.Start(); for (int i = 0; i < 500; i++) { Thread.Sleep(10); } }
/// <summary> /// 运行启动时的初始化任务 /// </summary> protected virtual void RunStartupTasks() { var typeFinder = _container.Resolve <ITypeFinder>(); var startUpTasks = typeFinder.ForTypesDerivedFrom <IStartupTask>() .ToInstances <IStartupTask>() .OrderBy(s => s.Order) .ToList(); foreach (var startUpTask in startUpTasks) { startUpTask.Execute(); } }
public object GetService(Type serviceType, string contract = null) { try { return(string.IsNullOrEmpty(contract) ? _container.Resolve(serviceType) : _container.ResolveNamed(contract, serviceType)); } catch (DependencyResolutionException) { return(null); } }
/// <summary> /// 创建对象 /// </summary> /// <typeparam name="T">对象类型</typeparam> public T Create <T>() { try { LoadHttpContextAccessor(); } catch { return(_container.Resolve <T>()); } if (_accessor?.HttpContext?.RequestServices != null) { return(_accessor.HttpContext.RequestServices.GetService <T>()); } return(_container.Resolve <T>()); }
protected override void Configure() { CreateContainer(); ExtendConventions(); ApplyBindingCulture(); SetupUIAutomation(); LoggingConfig.SetupCaliburnMicroLogging(); var newHandler = container.Resolve <AppExceptionHandler>(); //TODO: Yuck! Fix the ExceptionHandler dependencies to get around this var defaultHandler = ExceptionHandler.HandleException; ExceptionHandler.HandleException = ex => newHandler.Handle(ex, defaultHandler); }
public IServiceProvider ConfigureServices(IServiceCollection services) { // Configure logging new LogService().ConfigureLogging(new ServiceLogging()); services.AddSingleton <ILoggerFactory>((_) => new ServiceLoggerFactory()); // Register assemblies for discovery ConcreteServices.RegisterAssemblyForDiscovery(); // Load services by convention var builder = new ContainerBuilder(); var config = new ServiceDependencies(builder); new PangulServiceConventions().RegisterAll(config, config); new ServiceLocalDependencies().RegisterAll(config, config); new ServiceLocator(ServiceMatchExpression).RegisterAllByConvention(builder); // 3rd-party builder.RegisterType <FileSystem>().AsImplementedInterfaces(); // Load asp.net core services services.AddRouting(); services.AddControllers() .AddFluentValidation() .AddNewtonsoftJson(); new ServiceExtensions() .AddCors(services) .AddGlobalExceptionHandler(services); // Configure web auth var authService = new ServicePolicyList().AddAuthorization(services); services.AddSingleton(authService); // Convert to autofac builder.Populate(services); _container = builder.Build(); // Configure pangul auth var authBuilder = _container.Resolve <IPangulAuthServiceBuilder>(); var userService = _container.Resolve <IUserService>(); authBuilder.ConfigureProvider(new ServiceIdentityList(userService)); authBuilder.Build(_container.Resolve <IPangulAuthService>()); // Bind autofac as service provider return(new AutofacServiceProvider(_container)); }
protected override void OnStartup(StartupEventArgs e) { Logger.Trace("OnStartup: Invoked"); _pipeServerWorker.DoWork += (sender, args) => { Logger.Trace("OnStartup: Registering event handlers"); _pipeServer.DeskbandMouseEnter += (o, eventArgs) => this.Dispatcher.BeginInvoke(new Action(OnMouseEnter)); _pipeServer.DeskbandMouseLeave += (o, eventArgs) => this.Dispatcher.BeginInvoke(new Action(OnMouseLeave)); _pipeServer.DeskbandLeftButtonClick += (o, eventArgs) => this.Dispatcher.BeginInvoke(new Action(OnLButtonClick)); _pipeServer.DeskbandRightButtonClick += (o, eventArgs) => this.Dispatcher.BeginInvoke(new Action(OnRButtonClick)); _pipeServer.DeskbandExit += (o, eventArgs) => this.Dispatcher.BeginInvoke(new Action(OnExit)); _pipeServer.HookFinished += (o, eventArgs) => this.Dispatcher.BeginInvoke(new Action(OnDeskbandShown)); _pipeServer.Start(); }; _pipeServerWorker.RunWorkerAsync(); ShowDeskband(); var splashWindow = _container.Resolve <SplashWindow>(); splashWindow.Show(); splashWindow.Focus(); Logger.Trace("OnStartup: Splash window in on"); Task.Run(() => { _pipeServer.Send("ics_loading"); _container.Resolve <ISplashViewModel>().Start(); }).ContinueWith(t => { _pipeServer.Send("ics_on"); this.Dispatcher.BeginInvoke(new Action(() => { splashWindow.Close(); Logger.Trace("OnStartup: Splash window in off"); var successWindow = _container.Resolve <SuccessWindow>(); successWindow.DataContext = _container.Resolve <ISuccessViewModel>(); successWindow.Show(); successWindow.Focus(); Logger.Trace("OnStartup: Success window in on"); _currentWindow = successWindow; })); }); _mainWindow = _container.Resolve <MainWindow>(); _mainWindow.DataContext = _container.Resolve <IMainViewModel>(); _statusWindow = _container.Resolve <StatusWindow>(); _statusWindow.DataContext = _container.Resolve <IStatusViewModel>(); }
public dynamic Create(string name) { var _services = _container.ComponentRegistry.Registrations.SelectMany(f => f.Services).OfType <IServiceWithType>(); foreach (var item in _services) { // Trace.WriteLine(item.ServiceType.Name); if (item.ServiceType.Name.Equals(name)) { return(_container.Resolve(item.ServiceType)); } } ; return(null); }
protected override object GetInstance(Type serviceType, string key) { if (string.IsNullOrWhiteSpace(key)) { if (container.IsRegistered(serviceType)) { return(container.Resolve(serviceType)); } } else if (container.IsRegisteredWithKey(key, serviceType)) { return(container.ResolveKeyed(key, serviceType)); } throw new Exception($"Could not locate any instances of contract {key ?? serviceType.Name}."); }
private void ShowView() { try { Status = string.Empty; var bootstrapper = new Bootstrapper(); Autofac.IContainer container = bootstrapper.Bootstrap(); var mainWindow = container.Resolve <MainWindow>(); if (App.Current.Windows.OfType <LoginWindow>().FirstOrDefault() is LoginWindow) { (App.Current.Windows.OfType <LoginWindow>().FirstOrDefault() as LoginWindow).Hide(); } mainWindow.ShowDialog(); if ((App.Current.Windows.OfType <LoginWindow>().FirstOrDefault() as LoginWindow) != null) { (App.Current.Windows.OfType <LoginWindow>().FirstOrDefault() as LoginWindow).Close(); } } catch (SecurityException) { Status = "Вы не авторизованы!"; } }
public async Task CollectAndShowAsync(IContainer container, bool isIntegrationTest) { var errorsAndInfos = new ErrorsAndInfos(); var secretRepository = container.Resolve <ISecretRepository>(); CalculationLogger.ClearLogs(); var allPostings = await PostingCollector.CollectPostingsAsync(container, isIntegrationTest); var postingClassificationsSecret = await secretRepository.GetAsync(new PostingClassificationsSecret(), errorsAndInfos); if (errorsAndInfos.AnyErrors()) { await DataPresenter.WriteErrorsAsync(errorsAndInfos); return; } var postingClassifications = postingClassificationsSecret.Cast <IPostingClassification>().ToList(); await SummaryCalculator.CalculateAndShowSummaryAsync(allPostings, postingClassifications); await AverageCalculator.CalculateAndShowAverageAsync(allPostings, postingClassifications); await MonthlyDeltaCalculator.CalculateAndShowMonthlyDeltaAsync(allPostings, postingClassifications); await ClassifiedPostingsCalculator.CalculateAndShowClassifiedPostingsAsync(allPostings, postingClassifications, DateTime.Now.AddYears(-1), 70); CalculationLogger.Flush(); }
private Localizer GetLocalizer() { var workContextAccessor = container.Resolve <IWorkContextAccessor>(); var workContext = workContextAccessor.GetContext(); return(LocalizationUtilities.Resolve(workContext, localizerScope)); }
public void TestMethod1() { var entype = _container.Resolve <IEntypeRepository>(); var mapper = _container.Resolve <IMapper>(); //实例化依赖注入mock对象 var controller = new MapperController(mapper, entype); var result = (controller.Get()).Result; var json = result as JsonResult <List <EntypeModel> >; foreach (var item in json.Content) { Console.WriteLine(item.Name); } Assert.IsNotNull(result); }
public ApplicationCore(IContainer c) { container = c; model = container.Resolve<Model>(); logService = container.Resolve<LogService>(); connectionController = c.Resolve<ConnectionController>(); //Don't send two request went doing a post.. ServicePointManager.Expect100Continue = false; //Don't limit connections to a single node - 100 I think is the upper limit. ServicePointManager.DefaultConnectionLimit = 100; //System.Net.ServicePointManager.MaxServicePointIdleTime = 20000000; updateChecker = container.Resolve<UpdateCheckerService>(); interfaceController = container.Resolve<InterfaceController>(); overlordManagerService = container.Resolve<OverlordManagerService>(); singleInstanceService = new SingleInstanceService("FAP"); registerProtocolService = new RegisterProtocolService(); }
public Searcher() { Autofac.ContainerBuilder cb = new Autofac.ContainerBuilder(); /* cb.Register(c => new ClientServer(this)); cb.RegisterType<ClientServer>().As<ICommunication>(); cb.RegisterInstance(new ClientServer(this)); */ cb.Register(c => new EntityHandler()); cb.RegisterType<EntityHandler>().As<IDataBaseSearcher>(); cb.RegisterInstance(new EntityHandler()); Container = cb.Build(); // Communication = Container.Resolve<ClientServer>(); DataBase = Container.Resolve<EntityHandler>(); }
private static void Main() { AppDomain.CurrentDomain.UnhandledException += OnException; var cb = new ContainerBuilder(); cb.RegisterModule<BaseEditorsAutofacModule>(); cb.RegisterModule<MarmaladeEditorsAutofacModule>(); cb.RegisterModule<GenericSceneEditorsAutofacModule>(); cb.RegisterModule<AseAutofacModule>(); cb.RegisterModule<DaeAutofacModule>(); cb.RegisterModule<BspAutofacModule>(); cb.RegisterModule<SvgAutofacModule>(); cb.RegisterModule<MarmaladeAutofacModule>(); cb.RegisterModule<MarmaladeTextFilesAutofacModule>(); cb.RegisterModule<MarmaladeBinaryFilesAutofacModule>(); cb.RegisterModule<MarmaladeTextureFilesAutofacModule>(); cb.RegisterGeneric(typeof(BindingList<>)).UsingConstructor(new Type[] { }).As(typeof(IList<>)); //cb.RegisterGeneric(typeof(EditorConfiguration<>)).As(typeof(IEditorOptions<>)).SingleInstance(); cb.RegisterType<EditorEnvironment>().As<IEditorEnvironment>().SingleInstance(); cb.RegisterType<ResourceManager>().As<IResourceManager>().SingleInstance(); cb.RegisterType<ResourceFile>().As<IResourceFile>().InstancePerDependency(); cb.RegisterType<ResourceFileItem>().As<IResourceFileItem>().InstancePerDependency(); cb.RegisterType<EditorResourceErrorHandler>().As<IResourceErrorHandler>().SingleInstance(); cb.RegisterType<ToeGraphicsContext>().As<ToeGraphicsContext>().SingleInstance(); cb.RegisterInstance(OpenTkStreamConverterFactory.Default).As<IStreamConverterFactory>().SingleInstance(); cb.RegisterType<AddNewItemForm>().InstancePerDependency(); cb.RegisterType<MainEditorWindow>().SingleInstance(); using (container = cb.Build()) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(container.Resolve<MainEditorWindow>()); } }
public void Configure(IContainer container) { foreach (var strategy in Strategies) { if (strategy.IndicatorManager == null) strategy.IndicatorManager = container.Resolve<IndicatorManager>(); if (strategy.OrderManager == null) strategy.OrderManager = container.Resolve<OrderManager>(); if (strategy.InstrumentStrategy == null) strategy.InstrumentStrategy = this; foreach (var stopLoss in strategy.StopLosses) { if (stopLoss.IndicatorManager == null) stopLoss.IndicatorManager = container.Resolve<IndicatorManager>(); if (stopLoss.OrderManager == null) stopLoss.OrderManager = container.Resolve<OrderManager>(); if (stopLoss.InstrumentStrategy == null) stopLoss.InstrumentStrategy = this; } foreach (var stopProfit in strategy.StopProfits) { if (stopProfit.IndicatorManager == null) stopProfit.IndicatorManager = container.Resolve<IndicatorManager>(); if (stopProfit.OrderManager == null) stopProfit.OrderManager = container.Resolve<OrderManager>(); if (stopProfit.InstrumentStrategy == null) stopProfit.InstrumentStrategy = this; } } }
/// <summary> /// Initialization of the package; this method is called right after the package is sited, so this is the place /// where you can put all the initilaization code that rely on services provided by VisualStudio. /// </summary> protected override void Initialize() { Trace.WriteLine(string.Format(CultureInfo.CurrentCulture, "Entering Initialize() of: {0}", this)); base.Initialize(); var cb = new ContainerBuilder(); cb.RegisterModule<BaseEditorsAutofacModule>(); cb.RegisterModule<MarmaladeEditorsAutofacModule>(); cb.RegisterModule<GenericSceneEditorsAutofacModule>(); cb.RegisterModule<MarmaladeAutofacModule>(); cb.RegisterModule<AseAutofacModule>(); cb.RegisterModule<DaeAutofacModule>(); cb.RegisterModule<BspAutofacModule>(); cb.RegisterModule<MarmaladeTextFilesAutofacModule>(); cb.RegisterModule<MarmaladeBinaryFilesAutofacModule>(); cb.RegisterModule<MarmaladeTextureFilesAutofacModule>(); cb.RegisterGeneric(typeof(BindingList<>)).UsingConstructor(new Type[] { }).As(typeof(IList<>)); cb.RegisterType<VsEditorEnvironment>().As<IEditorEnvironment>().SingleInstance(); cb.RegisterType<ResourceManager>().As<IResourceManager>().SingleInstance(); cb.RegisterType<ResourceFile>().As<IResourceFile>().InstancePerDependency(); cb.RegisterType<ResourceFileItem>().As<IResourceFileItem>().InstancePerDependency(); cb.RegisterType<ResourceEditorFactory>().As<IResourceEditorFactory>().SingleInstance(); cb.RegisterType<EditorResourceErrorHandler>().As<IResourceErrorHandler>().SingleInstance(); cb.RegisterType<ToeGraphicsContext>().As<ToeGraphicsContext>().SingleInstance(); cb.RegisterType<EditorFactory>().As<IVsEditorFactory>().SingleInstance(); cb.RegisterInstance(this).As<Package>().As<ToeVisualStudioExtensionPackage>().ExternallyOwned(); container = cb.Build(); foreach (var f in container.Resolve<IEnumerable<IVsEditorFactory>>()) { //Create Editor Factory. Note that the base Package class will call Dispose on it. base.RegisterEditorFactory(f); } }
static ValidationResult Setup(SplashScreen splashScreen) { var validator = new SPFInstalledValidator(); if (validator.RunValidator() == ValidationResult.Error) { MessageBox.Show(validator.ErrorString+Environment.NewLine+Environment.NewLine+validator.QuestionString, SPMEnvironment.Version.Title + " Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return ValidationResult.Error; } var builder = new ContainerBuilder(); // Find all the assemblies for this application builder.RegisterModule(new AutoLoadAssemblies()); // Build the container now! autoFacContainer = builder.Build(); //CompositionProvider.LoadAssemblies(); IoCContainer = autoFacContainer.Resolve<IContainerAdapter>(); var provider = IoCContainer.Resolve<SettingsProvider>(); provider.Load(); var engine = new PreflightController(splashScreen, IoCContainer); if (!engine.Validate()) { return ValidationResult.Error; } Window = IoCContainer.Resolve<MainWindow>(); Window.SplashScreenLoad(splashScreen); return ValidationResult.Success; }
/// <summary> /// Do not override this method. This is where the IoC container is configured. /// </summary> /// <exception cref="NullReferenceException"> /// Either CreateFrameAdapter or CreateWindowManager or CreateEventAggregator or /// CreatePhoneApplicationServiceAdapter or CreateVibrateController or /// CreateSoundEffectPlayer is null. /// </exception> protected override void Configure() { // allow base classes to change bootstrapper settings ConfigureBootstrapper(); // validate settings if (CreateFrameAdapter == null) { throw new NullReferenceException("CreateFrameAdapter is not specified."); } if (CreateWindowManager == null) { throw new NullReferenceException("CreateWindowManager is not specified."); } if (CreateEventAggregator == null) { throw new NullReferenceException("CreateEventAggregator is not specified."); } if (CreatePhoneApplicationServiceAdapter == null) { throw new NullReferenceException( "CreatePhoneApplicationServiceAdapter is not specified."); } if (CreateVibrateController == null) { throw new NullReferenceException("CreateVibrateController is not specified."); } if (CreateSoundEffectPlayer == null) { throw new NullReferenceException("CreateSoundEffectPlayer is not specified."); } // Configure container. ContainerBuilder lBuilder = new ContainerBuilder(); // Register phone services. Assembly lCaliburnAssembly = typeof (IStorageMechanism).Assembly; // Register IStorageMechanism implementors. lBuilder.RegisterAssemblyTypes(lCaliburnAssembly) .Where( aType => typeof (IStorageMechanism).IsAssignableFrom(aType) && !aType.IsAbstract && !aType.IsInterface) .As<IStorageMechanism>() .InstancePerLifetimeScope(); // Register IStorageHandler implementors. lBuilder.RegisterAssemblyTypes(AssemblySource.Instance.ToArray()) .Where( aType => typeof (IStorageHandler).IsAssignableFrom(aType) && !aType.IsAbstract && !aType.IsInterface) .As<IStorageHandler>() .InstancePerLifetimeScope(); // Register view models. lBuilder.RegisterAssemblyTypes(AssemblySource.Instance.ToArray()) // Must be a type with a name that ends with ViewModel. .Where(aType => aType.Name.EndsWith("ViewModel")) // Mmust be in a namespace ending with ViewModels. .Where( aType => !EnforceNamespaceConvention || (!string.IsNullOrEmpty(aType.Namespace) && aType.Namespace.EndsWith("ViewModels"))) // Must implement INotifyPropertyChanged (deriving from PropertyChangedBase will statisfy this). .Where(aType => aType.GetInterface(ViewModelBaseType.Name, false) != null) // Registered as self. .AsSelf() // Subscribe on Activated event for viewmodels to make storage mechanism work. .OnActivated(aArgs => ActivateInstance(aArgs.Instance)) // Always create a new one. .InstancePerDependency(); // Register views. lBuilder.RegisterAssemblyTypes(AssemblySource.Instance.ToArray()) // Must be a type with a name that ends with View. .Where(aType => aType.Name.EndsWith("View")) // Must be in a namespace that ends in Views. .Where( aType => !EnforceNamespaceConvention || (!string.IsNullOrEmpty(aType.Namespace) && aType.Namespace.EndsWith("Views"))) // Registered as self. .AsSelf() // Always create a new one. .InstancePerDependency(); // Register the singletons. lBuilder.Register<IPhoneContainer>( aContext => new AutofacPhoneContainer(aContext.Resolve<IComponentContext>())) .SingleInstance(); lBuilder.RegisterInstance<INavigationService>(CreateFrameAdapter()) .SingleInstance(); PhoneApplicationServiceAdapter lPhoneService = CreatePhoneApplicationServiceAdapter(); lBuilder.RegisterInstance<IPhoneService>(lPhoneService) .SingleInstance(); lBuilder.Register(aContext => CreateEventAggregator()) .SingleInstance(); lBuilder.Register(aContext => CreateWindowManager()) .SingleInstance(); lBuilder.Register(aContext => CreateVibrateController()) .SingleInstance(); lBuilder.Register(aContext => CreateSoundEffectPlayer()) .SingleInstance(); lBuilder.RegisterType<StorageCoordinator>().AsSelf() .SingleInstance(); lBuilder.RegisterType<TaskController>().AsSelf() .SingleInstance(); // Allow derived classes to add to the container. ConfigureContainer(lBuilder); // Build the container Container = lBuilder.Build(); // Get the phone container instance. PhoneContainer = (AutofacPhoneContainer) Container.Resolve<IPhoneContainer>(); // Start the storage coordinator. StorageCoordinator lStorageCoordinator = Container.Resolve<StorageCoordinator>(); lStorageCoordinator.Start(); // Start the task controller. TaskController lTaskController = Container.Resolve<TaskController>(); lTaskController.Start(); // Add custom conventions for the phone. AddCustomConventions(); }