protected void Application_Start(object sender, EventArgs e) { #region Signalr var builder = new ContainerBuilder(); builder.RegisterHubs(Assembly.GetExecutingAssembly()).PropertiesAutowired(); builder.RegisterType <DebugLogger>().As <IHubLogger>(); var container = builder.Build(); var resolver = new AutofacDependencyResolver(container); GlobalHost.HubPipeline.AddModule(new LoggingPipelineModule(resolver.Resolve <IHubLogger>())); GlobalHost.HubPipeline.AddModule(new ErrorHandlingPipelineModule(resolver.Resolve <IHubLogger>())); var authorizer = new HubAuthorizeAttribute(); var module = new AuthorizeModule(authorizer, authorizer); GlobalHost.HubPipeline.AddModule(module); GlobalHost.HubPipeline.RequireAuthentication(); GlobalHost.DependencyResolver = new AutofacDependencyResolver(container); #endregion AutoMapperUtil.Execute(); //var aTimer = new System.Timers.Timer(); //aTimer.Elapsed += aTimer_Elapsed; //aTimer.Interval = 20000; //aTimer.Enabled = true; ValueProviderFactories.Factories.Remove(ValueProviderFactories.Factories.OfType <JsonValueProviderFactory>().FirstOrDefault()); ValueProviderFactories.Factories.Add(new JsonNetValueProviderFactory()); AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); ModelBundle.RegisterBindles(ModelBinders.Binders); ConsulUtil.StartWatchConsulServices(); }
/// <summary> /// 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 http://go.microsoft.com/fwlink/?LinkID=398940 /// </summary> /// <param name="services">The services.</param> public void ConfigureServices(IServiceCollection services) { // Add MVC services to the services container. // Build the intermediate service provider services.AddLocalization(options => options.ResourcesPath = "Resources"); services.AddAntiforgery(options => options.HeaderName = "X-XSRF-TOKEN"); services.AddScoped <ValidateMimeMultipartContentFilter>(); // Add functionality to inject IOptions<T> services.AddOptions(); // Add our Config object so it can be injected var appSettingsSection = Configuration.GetSection("AppSettings"); services.Configure <AppSettings>(appSettingsSection); services.Configure <AppSettings>(settings => { if (HttpContextAccessor.HttpContext == null) { return; } var request = HttpContextAccessor.HttpContext.Request; settings.Urls.Api = $"{request.Scheme}://{request.Host.ToUriComponent()}"; }); appSettingsSection.Bind(AppSettings); // *If* you need access to generic IConfiguration this is **required** services.AddSingleton(Configuration); ConfigAuth(services); // Enable Cors services.AddCors(options => { options.AddPolicy("CorsPolicy", builder => builder .AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader() .AllowCredentials() ); }); services.AddMvc(options => { //http://www.dotnetcurry.com/aspnet/1314/aspnet-core-globalization-localization options.Conventions.Add(new HybridModelBinderApplicationModelConvention()); options.Conventions.Add(new NameSpaceVersionRoutingConvention()); // Make authentication compulsory across the board (i.e. shut // down EVERYTHING unless explicitly opened up). var policy = new AuthorizationPolicyBuilder() .RequireAuthenticatedUser() .RequireClaim(ClaimTypes.Name) .RequireClaim(ClaimTypes.NameIdentifier) .Build(); options.Filters.Add(new AuthorizeFilter(policy)); } ).AddJsonOptions(opts => { // Force Camel Case to JSON opts.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); } ) .AddViewLocalization() .AddDataAnnotationsLocalization(); //https://www.billbogaiv.com/posts/hybrid-model-binding-in-aspnet-core-10-rc2 services.Configure <MvcOptions>(options => { /** * This is needed since the provider uses the existing `BodyModelProvider`. * Ref. https://github.com/aspnet/Mvc/blob/1.0.0-rc2/src/Microsoft.AspNetCore.Mvc.Core/ModelBinding/Binders/BodyModelBinder.cs */ var readerFactory = services.BuildServiceProvider().GetRequiredService <IHttpRequestStreamReaderFactory>(); options.ModelBinderProviders.Insert(0, new DefaultHybridModelBinderProvider(options.InputFormatters, readerFactory)); // options.Filters.Add(new CorsAuthorizationFilterFactory("CorsPolicy")); }); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Title = AppSettings.Information.Name, Version = AppSettings.Information.Version, Description = AppSettings.Information.Description, TermsOfService = AppSettings.Information.TermsOfService, Contact = new Contact { Name = AppSettings.Information.ContactName, Email = AppSettings.Information.ContactEmail }, License = new License { Name = AppSettings.Information.LicenseName, Url = AppSettings.Information.LicenseUrl } }); //Set the comments path for the swagger json and ui. var basePath = PlatformServices.Default.Application.ApplicationBasePath; var xmlPath = Path.Combine(basePath, "MasterApi.xml"); c.IncludeXmlComments(xmlPath); }); // Injection services.AddTransient <IHttpContextAccessor, HttpContextAccessor>(); services.Configure <RequestLocalizationOptions>( options => { var supportedCultures = new List <CultureInfo> { new CultureInfo("en"), new CultureInfo("en-US"), new CultureInfo("pt"), new CultureInfo("pt-BR") }; var defaultCulture = supportedCultures[1].Name; options.DefaultRequestCulture = new RequestCulture(defaultCulture, defaultCulture); options.SupportedCultures = supportedCultures; options.SupportedUICultures = supportedCultures; } ); // SignalR var authorizer = new HubAuthorizeAttribute(_tokenOptions); var module = new AuthorizeModule(authorizer, authorizer); services.AddSignalR(options => { options.EnableJSONP = true; options.Hubs.EnableJavaScriptProxies = true; options.Hubs.EnableDetailedErrors = true; options.Hubs.PipelineModules.Add(module); }); services.AddCustomHeaders(); var connString = Configuration.GetConnectionString("DbConnection"); //services.AddDbContext<DualAuthContext>(options => // options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); services.AddDbContext <AppDbContext>(options => { switch (AppSettings.DbSettings.InMemoryProvider) { case true: options.UseInMemoryDatabase(connString); break; default: options.UseSqlServer(connString, b => b.MigrationsAssembly("MasterApi.Data")); break; } }); services.AddHangfire(x => x.UseSqlServerStorage(connString)); // Repositories services.AddScoped(typeof(IDataContextAsync), typeof(AppDbContext)); services.AddScoped(typeof(IUnitOfWorkAsync), typeof(UnitOfWork)); services.AddScoped(typeof(IRepositoryAsync <>), typeof(Repository <>)); services.AddTransient <DataSeeder>(); //Services services.AddScoped(typeof(IService <>), typeof(Service <>)); services.AddScoped(typeof(IAuthService), typeof(AuthService)); services.AddScoped(typeof(IUserAccountService), typeof(UserAccountService)); services.AddScoped(typeof(INotificationService), typeof(NotificationService)); services.AddScoped(typeof(IGeoService), typeof(GeoService)); services.AddScoped(typeof(IUserProfileService), typeof(UserProfileService)); services.AddScoped(typeof(ILookupService), typeof(LookupService)); //Infrastructure services.AddSingleton(typeof(ICrypto), typeof(DefaultCrypto)); services.AddSingleton(typeof(ISmsSender), typeof(SmsSender)); services.AddSingleton(typeof(IEmailSender), typeof(EmailSender)); services.AddSingleton(typeof(IRazorLightEngine), s => EngineFactory.CreatePhysical($"{Directory.GetCurrentDirectory()}\\Views")); var asm = Assembly.GetEntryAssembly(); var subjectFiles = asm.GetManifestResourceNames().Where(x => x.Contains("subjects.json")); var emailSubjects = new Dictionary <string, Dictionary <string, string> >(); subjectFiles.ForEach(file => { var domain = file.Split('.'); var subjects = asm.ParseFromJson(file); emailSubjects.Add(domain[3], subjects); }); services.AddSingleton(typeof(IEmailSubjects), emailSubjects); services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>(); //Identity services.AddScoped(typeof(IUserInfo), s => new UserIdentityInfo(s.GetService <IHttpContextAccessor>().HttpContext.User)); }