public async Task StartAsync(CancellationToken cancellationToken) { _logger.LogInformation("Orleans Silo starting..."); var builder = new SiloHostBuilder() .Configure <ClusterOptions>(options => { options.ClusterId = _orleansConfig.ClusterId; options.ServiceId = Constants.ServiceId; }) .Configure <GrainCollectionOptions>(options => { options.CollectionAge = TimeSpan.FromMinutes(5); }) .ConfigureApplicationParts(parts => { parts.AddApplicationPart(typeof(IGrainMarker).Assembly).WithReferences(); }) .ConfigureServices(svcCollection => { ConfigureServices.RegisterServices(_configuration, svcCollection); }) .UsePerfCounterEnvironmentStatistics() .UseDashboard(options => { options.Port = _orleansConfig.OrleansDashboardPort; options.CounterUpdateIntervalMs = 10000; }); ConfigureClustering(builder); ConfigureLoadShedding(builder); ConfigureLogging(builder); _silo = builder.Build(); await _silo.StartAsync(cancellationToken); }
public void Setup() { _service = new ConfigureServices(); _service.ConfigureEFCore(); _service.ConfigureEFCoreInMemory(); }
public ContentSearchTestFixture() { _services = new ConfigureServices(); database = new Db("master"); ContentSearchManager.SearchConfiguration.Indexes.Clear(); ContentSearchManager.SearchConfiguration.Indexes.Add("sitecore_master_index", Substitute.For <ISearchIndex>()); }
public SwMacroFeatureDefinition() { string provider = ""; this.GetType().TryGetAttribute <MissingDefinitionErrorMessage>(a => { provider = a.Message; }); m_Provider = provider; var svcColl = new ServiceCollection(); svcColl.AddOrReplace <IXLogger>(() => new TraceLogger($"xCad.MacroFeature.{this.GetType().FullName}")); svcColl.AddOrReplace <IIconsCreator>(() => new BaseIconsCreator()); ConfigureServices?.Invoke(this, svcColl); OnConfigureServices(svcColl); m_SvcProvider = svcColl.CreateProvider(); m_Logger = m_SvcProvider.GetService <IXLogger>(); CustomFeatureDefinitionInstanceCache.RegisterInstance(this); var iconsConv = m_SvcProvider.GetService <IIconsCreator>(); iconsConv.KeepIcons = true; iconsConv.IconsFolder = MacroFeatureIconInfo.GetLocation(this.GetType()); TryCreateIcons(iconsConv); }
public MainPage() { this.InitializeComponent(); viewModel = ConfigureServices.Container().Resolve <IMainViewModel>(); Loaded += async(sender, arguments) => await viewModel.LoadEntries(); }
public HttpClient GetClient() => _factory.WithWebHostBuilder(b => b.ConfigureServices(s => { s.Replace(ServiceDescriptor.Singleton <IShortrStore, InMemoryShortrStore>()); s.Configure <ShortrOptions>(o => ShortrOptionsConfiguration?.Invoke(o)); ConfigureServices?.Invoke(s); })).CreateClient(WebApplicationFactoryClientOptions);
public HttpClient GetClient() { _factory = _factory.WithWebHostBuilder(c => c.ConfigureServices(s => { _defaultMocks(s); ConfigureServices?.Invoke(s); })); ServiceProvider = _factory.Services; return(_factory.CreateClient()); }
private static ServiceProvider SetupContainer() { var container = new ServiceCollection(); ConfigureServices.Configure(container); container.AddTransient <IGameControl, GameControl>(); return(container.BuildServiceProvider()); }
public static TestStartup Build(FileTypes fileType = FileTypes.JSON) { var serviceCollection = new ServiceCollection(); var configBuilder = new ConfigurationBuilder(); configBuilder.AddInMemoryCollection( new List <KeyValuePair <string, string> > { new KeyValuePair <string, string>(LOGGING_CONSOLE_LOGLEVEL, LogLevel.Debug.ToString()), new KeyValuePair <string, string>(LOGGING_TRACEWRITER_LOGLEVEL, LogLevel.Trace.ToString()), new KeyValuePair <string, string>(SETTINGS_SYNC_SETTINGS_FILE_TYPE, fileType.ToString()), new KeyValuePair <string, string>(SETTINGS_SYNC_SETTINGS_FILE_OTHER_PROVIDER, typeof(YamlPersistenceProvider).FullName), new KeyValuePair <string, string>(SETTINGS_SYNC_SETTINGS_FILE_OTHER_PROVIDER_ASSEMBLY, "GPS.SettingsSync.FilePersistence.Yaml"), new KeyValuePair <string, string>(SETTINGS_SYNC_SETTINGS_FILE_EXTENSION, "yaml"), new KeyValuePair <string, string>(SETTINGS_SYNC_DEFAULT_PATH_LOCAL, ".\\TestData\\Local"), new KeyValuePair <string, string>(SETTINGS_SYNC_DEFAULT_PATH_ROAMING, ".\\TestData\\Roaming"), new KeyValuePair <string, string>(Constants.SETTINGS_USE_FILE, true.ToString()), }); ConfigureTests?.Invoke(configBuilder); Configuration = configBuilder.Build(); ConfigureServices?.Invoke(serviceCollection, Configuration); serviceCollection .AddSingleton <IConfiguration>(provider => Configuration) .AddSingleton <ISettingsMetadata>(provider => { var data = provider.GetService <SerializationData>(); var localData = data.Sets[0]; var roamingData = data.Sets[1]; return(new Metadata(Assembly.GetEntryAssembly()?.GetName().Name, defaultLocalData: localData, defaultRoamingData: roamingData)); }) .AddTransient <TestStartup, TestStartup>() .AddTransient <SerializationData, SerializationData>() .AddGenerators() .AddDistributedApplicationData() .AddFilePersistenceManager() .AddYamlProvider() .AddLogging(builder => { builder .AddConfiguration(Configuration) .AddDebug(); }); Provider = serviceCollection.BuildServiceProvider(true); return(Provider.GetService <TestStartup>()); }
void IStartup.ConfigureServices(IServiceCollection services) { try { ConfigureServices?.Invoke(services); } catch (Exception ex) { Logger.Error(ex, ConfigureServices?.Method?.Name); } }
public bool ConnectToSW(object ThisSW, int cookie) { m_IsDisposed = false; try { var app = ThisSW as ISldWorks; AddInId = cookie; if (app.IsVersionNewerOrEqual(Enums.SwVersion_e.Sw2015)) { app.SetAddinCallbackInfo2(0, this, AddInId); } else { app.SetAddinCallbackInfo(0, this, AddInId); } m_Application = new SwApplication(app); m_Application.FirstStartupCompleted += OnStartupCompleted; var svcCollection = GetServicesCollection(); ConfigureServices?.Invoke(this, svcCollection); OnConfigureServices(svcCollection); m_SvcProvider = svcCollection.CreateProvider(); Logger = m_SvcProvider.GetService <IXLogger>(); m_Application.Init(svcCollection); Logger.Log("Loading add-in"); SwMacroFeatureDefinition.Application = m_Application; m_CommandManager = new SwCommandManager(Application, AddInId, m_SvcProvider, this.GetType().GUID); Connect?.Invoke(this); OnConnect(); return(true); } catch (Exception ex) { Logger.Log(ex); return(false); } }
public LoginViewModel() { client = ConfigureServices.Container().Resolve <IDataProvider>(); var loginCredential = GetCredentialFromLocker(); if (loginCredential != null) { loginCredential.RetrievePassword(); Email = loginCredential.UserName; Password = loginCredential.Password; Login(); } }
public static int Main(string[] args) { Configuration = ConfigureConfiguration.Execute(); var services = ConfigureServices.Execute(new ServiceCollection(), Configuration); var app = new CommandLineApplication <Program>(); app.Conventions .UseDefaultConventions() .UseConstructorInjection(services); return(app.Execute(args)); }
static async Task Main() { var builder = new HostBuilder() .ConfigureAppConfiguration(x => { var configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", false, true) .Build(); x.AddConfiguration(configuration); }) .ConfigureLogging(x => { x.AddConsole(); x.SetMinimumLevel(LogLevel.Debug); }) .ConfigureDiscordHost((context, config) => { config.SocketConfig = new DiscordSocketConfig { LogLevel = LogSeverity.Debug, AlwaysDownloadUsers = true, MessageCacheSize = 200 }; Statics.Config = context.Configuration; config.Token = context.Configuration[Statics.DiscordToken]; }) .UseCommandService((context, config) => { config.CaseSensitiveCommands = false; config.LogLevel = LogSeverity.Debug; config.DefaultRunMode = RunMode.Async; }) .ConfigureServices((context, services) => { ConfigureServices.RegisterServices(services); }) .UseConsoleLifetime(); var host = builder.Build(); using (host) { await host.RunAsync(); } }
private void OnConfigureExtensionServices(IXServiceConsumer sender, IXServiceCollection svcColl) { var builder = new ContainerBuilder(); builder.Populate(svcColl); ConfigureHostServices(builder); ConfigureServices?.Invoke(new ContainerBuilderWrapper(builder)); m_SvcProvider = new ServiceProvider(builder.Build()); svcColl.Populate(m_SvcProvider.Context); Initialized?.Invoke(m_App, m_SvcProvider, m_Modules); }
private void OnConfigureExtensionServices(IXServiceConsumer sender, IXServiceCollection svcColl) { var builder = new ContainerBuilder(); builder.Populate(svcColl); ConfigureHostServices(builder); ConfigureServices?.Invoke(new ContainerBuilderWrapper(builder)); m_SvcProvider = new ServiceProvider(builder.Build()); svcColl.Populate(m_SvcProvider.Container); m_PageCreator = m_SvcProvider.Container.Resolve <IPropertyPageCreator>(); }
private IWebHost Build(IReadOnlyCollection <string> hostnames) { if (_host != default) { throw new RedHttpServerException("The server is already running"); } Initialize(); var urls = hostnames.Count != 0 ? hostnames.Select(url => $"http://{url}:{Port}").ToArray() : new[] { $"http://localhost:{Port}" }; return(new WebHostBuilder() .UseKestrel() .ConfigureServices(services => { services.AddRouting(); ConfigureServices?.Invoke(services); }) .Configure(app => { if (!string.IsNullOrWhiteSpace(_publicRoot) && Directory.Exists(_publicRoot)) { var fullPublicPath = Path.GetFullPath(_publicRoot); app.UseFileServer(new FileServerOptions { FileProvider = new PhysicalFileProvider(fullPublicPath) }); Console.WriteLine($"Public files directory: {fullPublicPath}"); } if (_useWebSockets) { app.UseWebSockets(); } app.UseRouter(routeBuilder => { foreach (var route in _routes) { route(routeBuilder); } _routes.Clear(); }); ConfigureApplication?.Invoke(app); }) .UseUrls(urls) .Build()); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { ConfigureServices configureServices = new ConfigureServices(services); services.AddControllers(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "Plants.API", Version = "v1" }); }); services.AddCors(options => { options.AddPolicy("CorsPolicy", builder => builder .AllowAnyHeader() .AllowAnyMethod() .SetIsOriginAllowed((host) => true) .AllowCredentials()); }); services.AddDbContext <PlantsDbContext>(options => options.UseSqlServer( Configuration["ConnectionStrings:DefaultConnection"], optionsBuilder => optionsBuilder.MigrationsAssembly("Plants.API"))); services.Configure <JwtConfig>(Configuration.GetSection("JwtConfig")); services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(jwt => { var key = Encoding.ASCII.GetBytes(Configuration["JwtConfig:Secret"]); jwt.SaveToken = true; jwt.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, // this will validate the 3rd part of the jwt token using the secret that we added in the appsettings and verify we have generated the jwt token IssuerSigningKey = new SymmetricSecurityKey(key), // Add the secret key to our Jwt encryption ValidateIssuer = false, ValidateAudience = false, RequireExpirationTime = false, ValidateLifetime = true }; }); }
private static IHostBuilder CreateHostBuilder(string[] args, string directoryConfig) => Host.CreateDefaultBuilder(args) .ConfigureAppConfiguration((context, builder) => { builder .AddJsonFile($"{directoryConfig}sharedappsettings.json", optional: false, reloadOnChange: false) .AddJsonFile($"{directoryConfig}appsettings.json", optional: false, reloadOnChange: false); }) .UseWindowsService() .UseSerilog((context, loggerConfiguration) => { loggerConfiguration.ReadFrom.Configuration(context.Configuration); }) .ConfigureServices((hostContext, services) => { services.AddOptions(); ConfigureServices.RegisterServices(hostContext.Configuration, services); services.AddHostedService <OrleansSiloHost>(); });
/// <summary> /// Starts the server /// The server will handle requests for hostnames /// Protocol and port will be added automatically /// </summary> /// <param name="hostnames">The host names the server is handling requests for</param> public void Start(params string[] hostnames) { Initialize(); var urls = hostnames.Select(url => $"http://{url}:{Port}").ToArray(); var host = new WebHostBuilder() .UseKestrel() .ConfigureServices(s => { if (CorsPolicy != null) { s.AddCors(options => options.AddPolicy("CorsPolicy", ConfigurePolicy)); } s.AddRouting(); ConfigureServices?.Invoke(s); }) .Configure(app => { if (CorsPolicy != null) { app.UseCors("CorsPolicy"); } if (!string.IsNullOrWhiteSpace(_publicRoot) && Directory.Exists(_publicRoot)) { app.UseFileServer(new FileServerOptions { FileProvider = new PhysicalFileProvider(Path.GetFullPath(_publicRoot)) }); } if (_wsHandlers.Any()) { app.UseWebSockets(); } app.UseRouter(SetRoutes); }) .UseUrls(urls) .Build(); host.Start(); Console.WriteLine($"RedHttpServer/{Version} running on port " + Port); }
public void Init() { Provider = ConfigureServices.GetInMemoryCacheServiceProvider(); EFSecondLevelCache.Core.EFServiceProvider.ApplicationServices = Provider; this.UnitOfWork = new SqlServerFullContext(ConfigurationManager.ConnectionStrings["RepoTest"].ConnectionString, Provider); //Options = new DbContextOptionsBuilder<SqlServerFullContext>().UseSqlServer(ConfigurationManager.ConnectionStrings["RepoTest"].ConnectionString).Options; //this.UnitOfWork = new SqlServerFullContext(Options); //using (var context = new SqlServerFullContext(Options)) //{ // context.Database.EnsureDeleted(); // context.Database.EnsureCreated(); //} this.ProductTest(); this.UnitOfWork.Commit(); }
public IRestServer Build() { if (Configuration == null) { Configuration = GetDefaultConfiguration(); } Services.AddSingleton(typeof(IConfiguration), Configuration); Services.AddSingleton <IRestServer, RestServer>(); Services.AddSingleton <IRouter, Router>(); Services.AddSingleton <IRouteScanner, RouteScanner>(); Services.AddTransient <IContentFolder, ContentFolder>(); ConfigureServices?.Invoke(Services); var provider = Services.BuildServiceProvider(); var server = provider.GetRequiredService <IRestServer>(); server.Router.Services = Services; server.RouteScanner.Services = Services; var factory = provider.GetService <ILoggerFactory>(); if (factory != null) { server.SetDefaultLogger(factory); } var assembly = GetType().Assembly.GetName(); server.GlobalResponseHeaders.Add("Server", $"{assembly.Name}/{assembly.Version} ({RuntimeInformation.OSDescription})"); ConfigureServer?.Invoke(server); return(server); }
private void Build(IReadOnlyCollection <string> hostnames) { if (_host != default) { throw new RedHttpServerException("The server is already running"); } Initialize(); var urls = hostnames.Count != 0 ? hostnames.Select(url => $"http://{url}:{Port}").ToArray() : new [] { $"http://localhost:{Port}" }; _host = new WebHostBuilder() .UseKestrel() .ConfigureServices(services => { services.AddRouting(); ConfigureServices?.Invoke(services); }) .Configure(app => { if (!string.IsNullOrWhiteSpace(_publicRoot) && Directory.Exists(_publicRoot)) { app.UseFileServer(new FileServerOptions { FileProvider = new PhysicalFileProvider(Path.GetFullPath(_publicRoot)) }); } if (_wsHandlers.Any()) { app.UseWebSockets(); } app.UseRouter(SetRoutes); ConfigureApplication?.Invoke(app); }) .UseUrls(urls) .Build(); }
public static async Task Run <THostedService>(string[] args, ConfigureServices configureServices = null) where THostedService : class, IHostedService { Serilog.Debugging.SelfLog.Enable(Console.Error); var cancellationTokenSource = new CancellationTokenSource(); AssemblyLoadContext.Default.Unloading += (cts) => cancellationTokenSource.Cancel(); Console.CancelKeyPress += (sender, cts) => cancellationTokenSource.Cancel(); var assembly = Assembly.GetExecutingAssembly(); IConfiguration configuration; using (var resourceStream = assembly.GetManifestResourceStream("ModuleWrapper.SerilogSettings.json")) { configuration = new ConfigurationBuilder() .AddJsonStream(resourceStream) .AddJsonFile("SerilogSettings.json", true) .AddJsonFile("appsettings.json", optional: true) .AddEnvironmentVariables() .AddCommandLine(args) .Build(); } Log.Logger = new LoggerConfiguration() .ReadFrom.Configuration(configuration) .CreateLogger(); LogContext.PushProperty("ModuleId", typeof(THostedService).Name); LogContext.PushProperty("FunctionId", nameof(Run)); var host = new HostBuilder() .UseDefaultServiceProvider((context, options) => { options.ValidateOnBuild = true; }) .ConfigureHostConfiguration(configHost => { configHost.SetBasePath(Directory.GetCurrentDirectory()); configHost.AddJsonFile("hostsettings.json", optional: true); configHost.AddEnvironmentVariables(); configHost.AddCommandLine(args); }) .ConfigureAppConfiguration((hostContext, configApp) => { configApp.AddJsonFile("appsettings.json", optional: true); configApp.AddJsonFile( $"appsettings.{hostContext.HostingEnvironment.EnvironmentName}.json", optional: true); configApp.AddEnvironmentVariables(); configApp.AddCommandLine(args); }) .ConfigureServices((hostContext, services) => { services.AddHostedService <THostedService>(); services.AddSingleton(cancellationTokenSource); configureServices?.Invoke(services, hostContext.Configuration); }) .UseSerilog() .UseConsoleLifetime() .Build(); await Task.WhenAny(host.RunAsync(), WhenCancelled(cancellationTokenSource.Token)); Log.Information("Exiting.."); }
public LoginPage() { this.InitializeComponent(); ViewModel = ConfigureServices.Container().Resolve <ILoginViewModel>(); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { ConfigureServices configureServices = new ConfigureServices(services); services.AddControllers(); services.AddCors(options => { options.AddPolicy("CorsPolicy", builder => builder .AllowAnyHeader() .AllowAnyMethod() .SetIsOriginAllowed((host) => true) .AllowCredentials()); }); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "HealthESB.API", Version = "v1" }); }); services.Configure <JwtConfig>(Configuration.GetSection("JwtConfig")); services.Configure <CacheConfiguration>(Configuration.GetSection("CacheConfiguration")); services.AddMemoryCache(); services.AddHangfire(x => x.UseSqlServerStorage(Configuration.GetConnectionString("DefaultConnection"))); services.AddHangfireServer(); services.AddDbContext <HealthESBDbContext>(options => options.UseSqlServer( Configuration["ConnectionStrings:DefaultConnection"], optionsBuilder => optionsBuilder.MigrationsAssembly("HealthESB.API")), ServiceLifetime.Singleton); services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(jwt => { var key = Encoding.ASCII.GetBytes(Configuration["JwtConfig:Secret"]); jwt.SaveToken = true; jwt.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, // this will validate the 3rd part of the jwt token using the secret that we added in the appsettings and verify we have generated the jwt token IssuerSigningKey = new SymmetricSecurityKey(key), // Add the secret key to our Jwt encryption ValidateIssuer = false, ValidateAudience = false, RequireExpirationTime = false, ValidateLifetime = true }; }); // For saving Token //services.AddAuthentication("Bearer") // .AddJwtBearer("Bearer", options => options.SaveToken = true); //HttpContext.GetTokenAsync("Bearer", "access_token"); //services.AddIdentity<IdentityUser, IdentityRole>() // .AddEntityFrameworkStores<HealthESBDbContext>() // .AddDefaultTokenProviders(); services.AddDefaultIdentity <IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true).AddRoles <IdentityRole>() .AddEntityFrameworkStores <HealthESBDbContext>(); services.AddScoped <IElasticService, ElasticService>(); services.AddScoped <IRabbitMqService, RabbitMqService>(); services.AddScoped <IDapperRepository, DapperRepository>(); services.AddSingleton <IConfiguration>(Configuration); Constants.TTAC_BaseUrl = Configuration["TTAC:BaseUrl"]; Constants.TTAC_UserName = Configuration["TTAC:UserName"]; Constants.TTAC_Password = Configuration["TTAC:Password"]; Constants.TTAC_RegisterApiName = Configuration["TTAC:RegisterApiName"]; Constants.TTAC_RegisterApiKey = Configuration["TTAC:RegisterApiKey"]; Constants.TTAC_CheckApiKey = Configuration["TTAC:CheckApiKey"]; Constants.TTAC_CheckApiName = Configuration["TTAC:CheckApiName"]; Constants.TTAC_ReactiveApiName = Configuration["TTAC:ReactiveApiName"]; Constants.TTAC_ReactiveApiKey = Configuration["TTAC:ReactiveApiKey"]; Constants.TokenExpirationHours = int.Parse(Configuration["JwtConfig:TokenExpirationHours"]); Constants.TokenKey = Configuration["JwtConfig:Secret"]; }
public override IServiceCollection AddProviderServices(IServiceCollection services) { ConfigureServices?.Invoke(services); return(FakeRelationalOptionsExtension.AddEntityFrameworkRelationalDatabase(services)); }