internal static void InitializeServices(ServiceRegistry services, IConfiguration config) { services .AddMvc() .SetCompatibilityVersion(CompatibilityVersion.Version_2_2) .AddJsonOptions( options => options.SerializerSettings.Converters.Add(new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AdjustToUniversal })); services .AddIdentityCore <AppUser>() .AddUserStore <AppUserStore>(); services.AddAutoMapper(typeof(ServiceInitializationService).Assembly); services.Configure <AppSettings>(config.GetSection(AppSettings.SectionKey)); InitializeCors(services); InitializeSecurity(services, config); InitializeLocalisation(services); services.Scan( scanner => { scanner.AssembliesFromApplicationBaseDirectory(); scanner.LookForRegistries(); }); }
// Take in Lamar's ServiceRegistry instead of IServiceCollection (it implements IServiceCollection) public void ConfigureContainer(ServiceRegistry services) { _logger.LogDebug("ConfigureServices method entered."); //Https //services.AddHsts(x => x.IncludeSubDomains = true); //services.AddHttpsRedirection(options => //{ // //options.RedirectStatusCode = StatusCodes.Status301MovedPermanently; // //options.HttpsPort = 5001; //}); //Add framework services. var mvcBuilder = services.AddMvc(); mvcBuilder.AddMvcOptions(options => options.OutputFormatters.Add(new Microsoft.AspNetCore.Mvc.Formatters.XmlDataContractSerializerOutputFormatter(new System.Xml.XmlWriterSettings() { NamespaceHandling = System.Xml.NamespaceHandling.OmitDuplicates, Async = true, OmitXmlDeclaration = false }))); //TODO: configure removal of namespacing in the resulting xml mvcBuilder.AddMvcOptions(options => options.ReturnHttpNotAcceptable = true); mvcBuilder.SetCompatibilityVersion(CompatibilityVersion.Version_2_2); // required for certain features like [ApiController] //var jsonFormatter = mvcBuilder. services.AddAutoMapper(); // Swagger services.AddCustomSwagger(); // In memory cache services.AddMemoryCache(); // Resilience Policies: services.AddResiliencePolicies(); // Data Access: services.AddRavenDb(); //Versioning: services.AddApiVersioning(options => { options.ReportApiVersions = true; options.AssumeDefaultVersionWhenUnspecified = false; options.DefaultApiVersion = new ApiVersion(1, 0); options.ApiVersionReader = new UrlSegmentApiVersionReader(); options.ApiVersionSelector = new CurrentImplementationApiVersionSelector(options); }); //Messaging: services.AddAwsSns(); // Generic sorting/filtering/paging services.AddSortFilterPaging(); }
public void ConfigureContainer(ServiceRegistry serviceRegistry) { serviceRegistry.Scan(scanner => { scanner.TheCallingAssembly(); scanner.WithDefaultConventions(); }); serviceRegistry.For(typeof(IPipelineBehavior <,>)).Add(typeof(LoggingBehavior <,>)); serviceRegistry.For(typeof(IPipelineBehavior <,>)).Add(typeof(ValidationBehavior <,>)); serviceRegistry.AddMediatR(typeof(Startup)); serviceRegistry.AddAutoMapper(typeof(MappingProfile)); }
//TODO: configure Lamar "WithDefaultConventions" to remove unneeded registrations public void ConfigureContainer(ServiceRegistry services) { services.AddSignalR(); services.AddMvc(); services.Scan(s => { //s.TheCallingAssembly(); //s.WithDefaultConventions(); s.AssemblyContainingType(typeof(HomePageCheckHandler)); s.ConnectImplementationsToTypesClosing(typeof(IRequestHandler <,>)); s.ConnectImplementationsToTypesClosing(typeof(INotificationHandler <>)); }); services.AddSingleton <ICommandsProcessor, CommandsProcessor>(); services.AddSingleton <ISchedulerService, SchedulerService>(); services.AddSingleton <IChecksRepository, MemoryCheckRepository>(); services.AddSingleton <IScheduleRepository, MemoryScheduleRepository>(); services.AddSingleton <IHostedService, CheckRegistrator>(); services.AddSingleton <ILoggerService, TextLoggerService>(); services.AddSingleton <ILogStashService, LogStashService>(); services.AddSingleton <IHttpRequestService, HttpRequestService>(); services.AddSingleton <INotificationsService, NotificationsService>(); services.AddTransient <ISignalRNotificationsService, SignalRNotificationsService>(); services.AddTransient <IResultHandlingService, ResultHandlingService>(); services.AddTransient <IUnitTestsProcessorService, UnitTestsProcessorService>(); services.AddTransient <IWebDriversFactory, SeleniumDriversFactory>(); services.AddTransient <ITelegramNotificationService, TelegramService>(); services.AddMediatR(typeof(HomePageCheckHandler).GetTypeInfo().Assembly); services.AddTransient(typeof(IPipelineBehavior <,>), typeof(LoggerDecorator <,>)); services.AddTransient(typeof(IPipelineBehavior <,>), typeof(CommandResultHandleDecorator <,>)); services.AddTransient(typeof(IPipelineBehavior <,>), typeof(SignalRDecorator <,>)); services.AddTransient(typeof(IPipelineBehavior <,>), typeof(NotificationsDecorator <,>)); services.AddTransient(typeof(IPipelineBehavior <,>), typeof(DataStoreDecorator <,>)); services.AddTransient(typeof(IPipelineBehavior <,>), typeof(CommandExceptionsDecorator <,>)); services.Configure <TelegramNotificationSettings>(Configuration.GetSection("TelegramNotificationSettings")); services.Configure <LoggerSettings>(Configuration.GetSection("LoggerSettings")); services.AddSpaStaticFiles(configuration => { configuration.RootPath = "ClientApp/dist"; }); services.AddAutoMapper(typeof(ChecksMappingProfile)); }
public void ConfigureContainer(ServiceRegistry services) { Debug.WriteLine("Startup.ConfigureContainer"); services.AddAutoMapper(typeof(Startup).Assembly); services.Scan( scanner => { scanner.AssembliesFromApplicationBaseDirectory(); scanner.LookForRegistries(); }); RegisterMocks(services); services.AddControllers(); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureContainer(ServiceRegistry services) { services.AddControllers(); services.Scan(s => { s.TheCallingAssembly(); s.WithDefaultConventions(); }); var assemblies = AppDomain .CurrentDomain .GetAssemblies() .Where(s => s.GetName().Name.StartsWith(nameof(Sigantha))) .ToArray(); // Auto Mapper services.AddAutoMapper(assemblies); // Mediatr services.AddMediatR(assemblies); services.Scan(scanner => { foreach (var assembly in assemblies) { scanner.Assembly(assembly); } scanner.ConnectImplementationsToTypesClosing(typeof(IRequestHandler <,>)); }); // Need to add one for mediatr to see all of them services.For <IRequestHandler <TimelineGet.Query, TimelineGet.Result> >().Use <TimelineGet.Handler>(); services.For <IMediator>().Use <Mediator>().Transient(); services.For <ServiceFactory>().Use(ctx => ctx.GetInstance); // Db Contexts services.AddDbContext <SiganthaContext>(ServiceLifetime.Transient); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureContainer(ServiceRegistry services) { services.AddControllers(); services.Scan(s => { s.TheCallingAssembly(); s.WithDefaultConventions(); }); var assemblies = AppDomain .CurrentDomain .GetAssemblies() .Where(s => s.GetName().Name.StartsWith(nameof(Conglomerate))) .ToArray(); // Auto Mapper services.AddAutoMapper(assemblies); // Services services.For <IIngredientService>().Use <IngredientService>(); // Repositories services.For <IIngredientRepository>().Use <IngredientRepository>(); // Mediatr services.AddMediatR(assemblies); services.Scan(scanner => { foreach (var assembly in assemblies) { scanner.Assembly(assembly); } scanner.ConnectImplementationsToTypesClosing(typeof(IRequestHandler <,>)); }); // For some reason we need to register one of the handlers for Lamar to register all of them services.For <IRequestHandler <IngredientGetAll.Query, IList <IngredientGetAll.Ingredient> > >().Use <IngredientGetAll.Handler>(); services.For <IMediator>().Use <Mediator>().Transient(); services.For <ServiceFactory>().Use(ctx => ctx.GetInstance); // Db Contexts services.AddDbContext <SandwichShopContext>(ServiceLifetime.Transient); // Hangfire services.AddHangfire(configuration => configuration .SetDataCompatibilityLevel(CompatibilityLevel.Version_170) .UseSimpleAssemblyNameTypeSerializer() .UseRecommendedSerializerSettings() .UseStorage(new MySqlStorage(Configuration.GetConnectionString("Hangfire"), new MySqlStorageOptions() { TransactionIsolationLevel = IsolationLevel.ReadCommitted, QueuePollInterval = TimeSpan.FromSeconds(1), JobExpirationCheckInterval = TimeSpan.FromHours(1), CountersAggregateInterval = TimeSpan.FromMinutes(5), PrepareSchemaIfNecessary = true, DashboardJobListLimit = 50000, TransactionTimeout = TimeSpan.FromMinutes(1), TablePrefix = "Hangfire" }))); services.AddHangfireServer(options => { // Order determines priority options.Queues = new[] { JobQueues.API, JobQueues.DEFAULT }; }); services.For <IJobFactory>().Use <JobFactory>(); }
// This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureContainer(ServiceRegistry services) { services.AddMiniProfiler(opt => { // opt.RouteBasePath = "/profiler"; opt.ShouldProfile = _ => true; opt.ShowControls = true; opt.StackMaxLength = short.MaxValue; opt.PopupStartHidden = false; opt.PopupShowTrivial = true; opt.PopupShowTimeWithChildren = true; }); services.AddHttpsRedirection(options => options.HttpsPort = 443); // Add framework services // Add functionality to inject IOptions<T> services.AddOptions(); services.AddResponseCompression(); services.AddLogging(); services.AddRouting(options => options.LowercaseUrls = true); services.AddDistributedMemoryCache(); services.AddSession(options => { // Set a short timeout for easy testing. options.IdleTimeout = TimeSpan.FromMinutes(60); options.Cookie.HttpOnly = true; options.Cookie.Name = ApiConstants.AuthenticationSessionCookieName; options.Cookie.SecurePolicy = CookieSecurePolicy.None; }); // Make sure a JS engine is registered, or you will get an error! services.AddJsEngineSwitcher(options => options.DefaultEngineName = ChakraCoreJsEngine.EngineName) .AddChakraCore(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = ApplicationName, Version = "v1" }); // Set the comments path for the Swagger JSON and UI. var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); if (File.Exists(xmlPath)) { c.IncludeXmlComments(xmlPath); } c.AddSecurityDefinition("Bearer", // Name the security scheme new OpenApiSecurityScheme { Description = "JWT Authorization header using the Bearer scheme.", Type = SecuritySchemeType.Http, Scheme = "bearer" }); }); services.AddMvc(x => { // Not need to have https x.RequireHttpsPermanent = false; // Allow anonymous for localhost if (_env.IsDevelopment()) { x.Filters.Add <AllowAnonymousFilter>(); } // Exception filter attribute x.Filters.Add <ExceptionFilterAttribute>(); }) .AddViewOptions(x => { x.HtmlHelperOptions.ClientValidationEnabled = true; }) .AddNewtonsoftJson(x => { x.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; x.SerializerSettings.Converters.Add(new StringEnumConverter { NamingStrategy = new CamelCaseNamingStrategy() }); x.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); x.SerializerSettings.ContractResolver = new IgnoreUserContractResolver(); }) .AddRazorPagesOptions(x => x.Conventions.ConfigureFilter(new IgnoreAntiforgeryTokenAttribute())); services.AddWebMarkupMin(opt => { opt.AllowMinificationInDevelopmentEnvironment = true; opt.AllowCompressionInDevelopmentEnvironment = true; }) .AddHtmlMinification() .AddHttpCompression(); // If using Kestrel: services.Configure <KestrelServerOptions>(options => { options.AllowSynchronousIO = true; }); // If using IIS: services.Configure <IISServerOptions>(options => { options.AllowSynchronousIO = true; }); services.AddDbContext <EntityDbContext>(opt => { if (_env.IsDevelopment()) { opt.UseSqlite(_configuration.GetValue <string>("ConnectionStrings:Sqlite")); } else { var postgresConnectionString = ConnectionStringUrlToPgResource(_configuration.GetValue <string>("DATABASE_URL") ?? throw new Exception("DATABASE_URL is null")); opt.UseNpgsql(postgresConnectionString); } }, ServiceLifetime.Transient); services.AddIdentity <User, IdentityRole <int> >(x => x.User.RequireUniqueEmail = true) .AddEntityFrameworkStores <EntityDbContext>() .AddRoles <IdentityRole <int> >() .AddDefaultTokenProviders(); // L2 EF cache if (_env.IsDevelopment()) { services.AddEFSecondLevelCache(options => options.UseEasyCachingCoreProvider("memory").DisableLogging(true) ); services.AddEasyCaching(options => options.UseInMemory("memory")); } else { services.AddEFSecondLevelCache(options => options.UseEasyCachingCoreProvider("redis").DisableLogging(true)); services.AddEasyCaching(options => { var(_, dictionary) = UrlUtility.UrlToResource(_configuration.GetValue <string>("REDISTOGO_URL")); // use memory cache with your own configuration options.UseRedis(x => { x.DBConfig.Endpoints.Add(new ServerEndPoint(dictionary["Host"], int.Parse(dictionary["Port"]))); x.DBConfig.Username = dictionary["Username"]; x.DBConfig.Password = dictionary["Password"]; x.DBConfig.AbortOnConnectFail = false; }); }); } services.AddEfRepository <EntityDbContext>(x => { x.Profiles(Assembly.Load("Dal"), Assembly.Load("Models")); }); services.AddAutoMapper(Assembly.Load("Models")); services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(x => { x.Cookie.MaxAge = TimeSpan.FromMinutes(60); x.LoginPath = new PathString("/Login/"); x.LogoutPath = new PathString("/Logout/"); }); services.For <GlobalConfigs>().Use(new GlobalConfigs()).Singleton(); // Initialize the email jet client services.For <IMailjetClient>().Use(new MailjetClient( _configuration.GetValue <string>("MAIL_JET_KEY"), _configuration.GetValue <string>("MAIL_JET_SECRET")) ).Singleton(); // If environment is localhost then use mock email service if (_env.IsDevelopment()) { services.For <IS3Service>().Use(new S3Service()).Singleton(); services.For <IEmailServiceApi>().Use(new EmailServiceApi()).Singleton(); } else { var(accessKeyId, secretAccessKey, url) = ( _configuration.GetRequiredValue <string>("CLOUDCUBE_ACCESS_KEY_ID"), _configuration.GetRequiredValue <string>("CLOUDCUBE_SECRET_ACCESS_KEY"), _configuration.GetRequiredValue <string>("CLOUDCUBE_URL") ); var prefix = new Uri(url).Segments.GetValue(1)?.ToString(); const string bucketName = "cloud-cube"; // Generally bad practice var credentials = new BasicAWSCredentials(accessKeyId, secretAccessKey); // Create S3 client services.For <IAmazonS3>().Use(new AmazonS3Client(credentials, RegionEndpoint.USEast1)); services.For <S3ServiceConfig>().Use(new S3ServiceConfig(bucketName, prefix)); services.For <IS3Service>().Use(ctx => new S3Service( ctx.GetInstance <ILogger <S3Service> >(), ctx.GetInstance <IAmazonS3>(), ctx.GetInstance <S3ServiceConfig>() )); services.For <MailGunConfig>().Use(new MailGunConfig { ApiKey = _configuration.GetRequiredValue <string>("MAILGUN_API_KEY"), Domain = _configuration.GetRequiredValue <string>("MAILGUN_DOMAIN") }); } // Register stuff in container, using the StructureMap APIs... services.Scan(_ => { _.AssemblyContainingType(typeof(Startup)); _.Assembly("Api"); _.Assembly("Logic"); _.Assembly("Dal"); _.WithDefaultConventions(); }); }