static void Main(string[] args) { Console.WriteLine("Dependency Injection Demo (3)"); Console.WriteLine("Alternative implementations and Guids"); Console.WriteLine("-------------------------------------"); var services = new ServiceCollection(); services.AddSingleton <IXMLWriter, XMLWriter>(); var provider = services.BuildServiceProvider(); var XMLInstance = provider.GetService <IXMLWriter>(); XMLInstance.WriteXML(); var XMLInstance2 = ServiceProviderServiceExtensions. GetService <IXMLWriter>(provider); XMLInstance2.WriteXML(); // Provider via DefaultServiceProviderFactory //var factory = new DefaultServiceProviderFactory(); //IServiceProvider prov = factory.CreateServiceProvider(services); // Provider via ServiceCollectionContainerBuilderExtensions //IServiceProvider prov = ServiceCollectionContainerBuilderExtensions. // BuildServiceProvider(services); //var XMLInstance = prov.GetService<IXMLWriter>(); //XMLInstance.WriteXML(); Console.ReadLine(); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { //app.UseDeveloperExceptionPage(); app.UseExceptionHandler("/Error"); } else { app.UseExceptionHandler("/Error"); } var provider = new FileExtensionContentTypeProvider(); provider.Mappings[".jsp"] = "text/html"; app.UseStaticFiles(new StaticFileOptions { ContentTypeProvider = provider }); app.UseCookiePolicy(); app.UseSession(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); GTXMethod.config = Configuration; GTXMethod.set = ServiceProviderServiceExtensions.GetRequiredService <YsbqcSetting>(app.ApplicationServices); }
public JsonResult ProductInformation([Bind(Prefix = "id")] string productId) { var service = ServiceProviderServiceExtensions.GetService <IVisitorContext>(ServiceLocator.ServiceProvider); var product = _arRepository.GetProductInformation(service, productId); return(Json(product, JsonRequestBehavior.AllowGet)); }
/// <summary> /// Called from <see cref="M:Microsoft.AspNetCore.Mvc.RequireHttpsAttribute.OnAuthorization(Microsoft.AspNetCore.Mvc.Filters.AuthorizationFilterContext)" /> if the request is not received over HTTPS. Expectation is /// <see cref="P:Microsoft.AspNetCore.Mvc.Filters.AuthorizationFilterContext.Result" /> will not be <c>null</c> after this method returns. /// </summary> /// <param name="filterContext">The <see cref="T:Microsoft.AspNetCore.Mvc.Filters.AuthorizationFilterContext" /> to update.</param> /// <remarks> /// If it was a GET request, default implementation sets <see cref="P:Microsoft.AspNetCore.Mvc.Filters.AuthorizationFilterContext.Result" /> to a /// result which will redirect the client to the HTTPS version of the request URI. Otherwise, default /// implementation sets <see cref="P:Microsoft.AspNetCore.Mvc.Filters.AuthorizationFilterContext.Result" /> to a result which will set the status /// code to <c>403</c> (Forbidden). /// </remarks> protected virtual void HandleRequest(AuthorizationFilterContext filterContext) { if (!string.Equals(filterContext.HttpContext.Request.Method, "GET", StringComparison.OrdinalIgnoreCase)) { filterContext.Result = (new StatusCodeResult(403)); } else { HttpRequest request = filterContext.HttpContext.Request; HostString host = default(HostString);// request.Host; string hostString = this.Host; IOptions <MvcOptions> requiredService = ServiceProviderServiceExtensions.GetRequiredService <IOptions <MvcOptions> >(filterContext.HttpContext.RequestServices); if (requiredService.Value.SslPort.HasValue && requiredService.Value.SslPort > 0) { host = new HostString(hostString, requiredService.Value.SslPort.Value); } else { host = new HostString(hostString); } bool permanent = _permanent ?? requiredService.Value.RequireHttpsPermanent; string[] obj = new string[5] { "https://", host.ToUriComponent(), request.PathBase.ToUriComponent(), request.Path.ToUriComponent(), request.QueryString.ToUriComponent() }; string url = string.Concat(obj); filterContext.Result = (new RedirectResult(url, permanent)); } }
private static IServiceCollection AddSwaggerInternal( this IServiceCollection services, string applicationName, Action <SwaggerGenOptions> configure = null) { services.AddApiVersioning((Action <ApiVersioningOptions>)(options => { options.ReportApiVersions = true; options.AssumeDefaultVersionWhenUnspecified = true; options.DefaultApiVersion = new ApiVersion(1, 0); })); services.AddVersionedApiExplorer((Action <ApiExplorerOptions>)(options => { options.GroupNameFormat = "'v'VVV"; options.SubstituteApiVersionInUrl = true; })); services.AddSwaggerGen((Action <SwaggerGenOptions>)(options => { foreach (ApiVersionDescription versionDescription in ServiceProviderServiceExtensions .GetRequiredService <IApiVersionDescriptionProvider>( ServiceCollectionContainerBuilderExtensions.BuildServiceProvider(services)) .ApiVersionDescriptions) { options.SwaggerDoc(versionDescription.GroupName, new OpenApiInfo() { Title = applicationName, Version = versionDescription.ApiVersion.ToString() }); } options.UseInlineDefinitionsForEnums(); options.MapType <Guid>((Func <OpenApiSchema>)(() => new OpenApiSchema() { Type = "string", Format = "uuid" })); options.MapType <Decimal>((Func <OpenApiSchema>)(() => new OpenApiSchema() { Type = "number", Format = "" })); options.MapType <Decimal?>((Func <OpenApiSchema>)(() => new OpenApiSchema() { Type = "number", Format = "" })); Action <SwaggerGenOptions> action = configure; if (action == null) { return; } action(options); })); return(services); }
/// <summary> /// Adds LiteX SQLite Cache manager services /// </summary> /// <param name="services"></param> /// <param name="config">SQLite configuration settings, default: use 'SQLiteConfig' from appsettings.json</param> /// <returns></returns> public static IServiceCollection AddLiteXSQLiteCache(this IServiceCollection services, SQLiteConfig config = null) { //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Expected O, but got Unknown //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) if (config == null) { IConfiguration requiredService = ServiceProviderServiceExtensions.GetRequiredService <IConfiguration>((IServiceProvider)ServiceCollectionContainerBuilderExtensions.BuildServiceProvider(services)); IConfigurationSection section = requiredService.GetSection(SQLiteCacheDefaults.SettingsSection); config = ((section != null) ? ConfigurationBinder.Get <SQLiteConfig>(section) : null); if (config == null) { config = new SQLiteConfig { FileName = SQLiteCacheDefaults.FileName, FilePath = SQLiteCacheDefaults.FilePath, OpenMode = 0, CacheMode = 0, EnableLogging = LiteXCacheDefaults.EnableLogging }; } config.FilePath = ((!string.IsNullOrWhiteSpace(config.FilePath)) ? config.FilePath : SQLiteCacheDefaults.FilePath); } return(services.AddLiteXSQLiteCache(delegate(SQLiteConfig option) { //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) option.FileName = config.FileName; option.FilePath = config.FilePath; option.OpenMode = config.OpenMode; option.CacheMode = config.CacheMode; })); }
public override void OnActionExecuting(ActionExecutingContext context) { //IL_00ce: Unknown result type (might be due to invalid IL or missing references) //IL_00d3: Unknown result type (might be due to invalid IL or missing references) //IL_00da: Unknown result type (might be due to invalid IL or missing references) //IL_00e1: Unknown result type (might be due to invalid IL or missing references) //IL_010d: Expected O, but got Unknown if (CurrentUser != null) { HttpContext httpContext = context.HttpContext; string text = httpContext.Request.Cookies["pc"]; if (text != null) { ((dynamic)this.ViewBag).UserPromotionCount = text; } else { IPromotionService service = ServiceProviderServiceExtensions.GetService <IPromotionService>(httpContext.RequestServices); Result <int> result = service.GetUserActivePromotionCount(CurrentUser.UserId).Result; int data = result.Data; IResponseCookies cookies = httpContext.Response.Cookies; string text2 = data.ToString(); CookieOptions val = new CookieOptions(); val.HttpOnly = (true); val.Secure = (true); val.Expires = ((DateTimeOffset?)DateTime.Now.AddMinutes(1.0)); cookies.Append("pc", text2, val); ((dynamic)this.ViewBag).UserPromotionCount = data.ToString(); } } base.OnActionExecuting(context); }
public Task<object> CreateDynamicRegionAsync(ContentTypeBase type, string regionId, bool managerInit = false) { V_0 = new ContentFactory.u003cu003ec__DisplayClass3_0(); V_0.regionId = regionId; V_1 = ServiceProviderServiceExtensions.CreateScope(this._services); try { V_2 = type.get_Regions().FirstOrDefault<RegionType>(new Func<RegionType, bool>(V_0.u003cCreateDynamicRegionAsyncu003eb__0)); if (V_2 == null) { V_3 = null; } else { V_3 = this.CreateDynamicRegionAsync(V_1, V_2, true, managerInit); } } finally { if (V_1 != null) { V_1.Dispose(); } } return V_3; }
private IShellPipeline BuildTenantPipeline() { V_0 = new ApplicationBuilder(ShellScope.get_Context().get_ServiceProvider(), this._features); stackVariable7 = ServiceProviderServiceExtensions.GetService <IEnumerable <IStartupFilter> >(V_0.get_ApplicationServices()); V_1 = new ShellRequestPipeline(); V_2 = new Action <IApplicationBuilder>(this.u003cBuildTenantPipelineu003eb__6_0); V_3 = stackVariable7.Reverse <IStartupFilter>().GetEnumerator(); try { while (V_3.MoveNext()) { V_2 = V_3.get_Current().Configure(V_2); } } finally { if (V_3 != null) { V_3.Dispose(); } } V_2.Invoke(V_0); V_1.set_Next(V_0.Build()); return(V_1); }
public async Task Invoke(HttpContext context, ILoggerFactory loggerFactory) { do { try { await _next(context); break; } catch (DbUpdateConcurrencyException) { var logger = loggerFactory .CreateLogger <DbUpdateConcurrencyExceptionHandlingMiddleware>(); if (context.Request.Body != null && context.Request.Body.CanSeek) { context.Request.Body.Seek(0, SeekOrigin.Begin); } logger.LogWarning($"Some concurrent query had time to update the state. Retry handling request process for {context.Request.Method} {context.Request.Path}:{context.TraceIdentifier}"); // Recreate scope for use new db context context.RequestServices = ServiceProviderServiceExtensions.CreateScope(context.RequestServices).ServiceProvider; continue; } } while (true); }
public static IServiceCollection AddSingletonFactory <T, TFactory>(this IServiceCollection collection) where T : class where TFactory : class, IServiceFactory <T> { collection.AddTransient <TFactory>(); return(AddInternal <T, TFactory>(collection, p => ServiceProviderServiceExtensions.GetRequiredService <TFactory>(p), ServiceLifetime.Singleton)); }
public static IApplicationBuilder UsePoweredBy(this IApplicationBuilder app, bool enabled, string headerValue) { stackVariable2 = ServiceProviderServiceExtensions.GetRequiredService <IPoweredByMiddlewareOptions>(app.get_ApplicationServices()); stackVariable2.set_Enabled(enabled); stackVariable2.set_HeaderValue(headerValue); return(app); }
protected static string[] GetDependencies(IDatabaseRepository databaseRepository) { if (databaseRepository == null) { databaseRepository = ServiceProviderServiceExtensions.GetService <IDatabaseRepository>(ServiceLocator.ServiceProvider); } return((databaseRepository.GetContentDatabase().Name.ToLower() == GlobalSettings.Database.Master) ? AssetContentRefresher.MasterCacheDependencyKeys : AssetContentRefresher.WebCacheDependencyKeys); }
public Task Execute(IJobExecutionContext context) { ILogger logger = ServiceProviderServiceExtensions.GetRequiredService <ILogger <DemoJob> >( ServiceProviderExtension.ServiceProvider); logger.LogInformation(string.Format("{0}执行一次", DateTime.Now)); return(Task.CompletedTask); }
public static IUniversalBuilder AddRequiredPlatformServices(this IUniversalBuilder builder) { Check.NotNull(builder); builder.Services.AddOptions(); builder.Services.TryAddSingleton(provider => ServiceProviderServiceExtensions.GetRequiredService <IOptions <UniversalOption> >(provider).Value); return(builder); }
public async Task <IValueProvider> BindAsync(BindingContext context) { await Task.Yield(); var scope = InjectBindingProvider.Scopes.GetOrAdd(context.FunctionInstanceId, (_) => ServiceProviderServiceExtensions.CreateScope(_serviceProvider)); var value = ServiceProviderServiceExtensions.GetRequiredService(scope.ServiceProvider, _type); return(await BindAsync(value, context.ValueContext)); }
public async Task Print() { ServiceCollection services = new(); services.AddSingleton <ILoggerFactory>(_ => NullLoggerFactory.Instance); new Startup().ConfigureServices(services); await using var provider = services.BuildServiceProvider(); var schema = ServiceProviderServiceExtensions.GetRequiredService <ISchema>(provider); SchemaPrinter printer = new(schema); var print = printer.Print(); await Verifier.Verify(print); }
public static void RegisterCache(this IServiceCollection services, IConfiguration configuration) { services.Configure <RedisSettings>(option => { var jsonFileConfig = configuration.GetSection(nameof(RedisSettings)); option.Host = jsonFileConfig.GetValue <string>(nameof(RedisSettings.Host)); option.Password = jsonFileConfig.GetValue <string>(nameof(RedisSettings.Password)); }); services.AddSingleton <IRedisStore, RedisStore>(); services.AddSingleton <IRedisClientFactory, RedisClientFactory>(); services.AddTransient(serviceProvider => ServiceProviderServiceExtensions.GetService <IRedisClientFactory>(serviceProvider).GetDatabase()); services.AddMemoryCache(setup => { setup.ExpirationScanFrequency = TimeSpan.FromMinutes(1); }); }
public async Task OnAuthorizationAsync(AuthorizationFilterContext context) { if (!context.ActionDescriptor.EndpointMetadata.Any(item => item is AllowNotConfirmed || item is AllowAnonymousFilter || item is IAllowAnonymous)) { if (!context.HttpContext.User.Identity.IsAuthenticated) { context.Result = new ForbidResult(); return; } try { var confirmed = context.HttpContext.User.HasClaim(CustomClaimTypes.AccountConfirmed, true.ToString()); //Make a call to database to ensure Consistency if (!confirmed) { BuildTrackerContext dbContext = ServiceProviderServiceExtensions.GetRequiredService <BuildTrackerContext>(context.HttpContext.RequestServices); var id = int.Parse(context.HttpContext.User.Identity?.Name); var user = await dbContext.FindAsync <User>(id); if (user == null) { context.Result = new UnauthorizedResult(); return; } else if (!user.AccountConfirmed) { var dic = new Dictionary <string, string> { { "Reason", "Account not Confirmed" }, { "AuthUrl", "api/users/confirm/" + user.Id } }; AuthenticationProperties props = new AuthenticationProperties(dic); var result = JsonConvert.SerializeObject(new { error = "Account not confirmed" }); await context.HttpContext.Response.WriteAsync(result); context.Result = new ForbidResult(props); return; } } } catch { context.Result = new ForbidResult(); return; } } }
public static IUserContext GetUserContext(this IServiceProvider container, IUserContext userContext) { IUserContext userContext1 = userContext; try { if (ServiceProviderServiceExtensions.GetService <IUserContextLoader>(container) != null) { ServiceProviderServiceExtensions.GetService <IUserContextLoader>(container).Load(userContext1); } } catch { } return(userContext1); }
/// <summary> /// Method to clear expired persisted grants. /// </summary> /// <returns></returns> public async Task RemoveExpiredGrantsAsync() { try { _logger.LogTrace("Querying for expired grants to remove"); var found = Int32.MaxValue; using (var serviceScope = _serviceProvider.GetRequiredService <IServiceScopeFactory>().CreateScope()) { var tokenCleanupNotification = ServiceProviderServiceExtensions.GetService <IOperationalStoreNotification>(serviceScope.ServiceProvider); { while (found >= _options.TokenCleanupBatchSize) { var expired = PersistedGrants.FindAllByExpirationAndBatchSize(_options.TokenCleanupBatchSize); found = expired.Count; _logger.LogInformation("Removing {grantCount} grants", found); if (found > 0) { try { expired.Delete(); if (tokenCleanupNotification != null) { await tokenCleanupNotification.PersistedGrantsRemovedAsync(expired); } } catch (Exception ex) { // we get this if/when someone else already deleted the records // we want to essentially ignore this, and keep working _logger.LogDebug("Concurrency exception removing expired grants: {exception}", ex.Message); } } } } } } catch (Exception ex) { _logger.LogError("Exception removing expired grants: {exception}", ex.Message); } }
/// <summary> /// Uses the SQLite cache. /// </summary> /// <returns>The SQLite cache.</returns> /// <param name="app">App.</param> public static IApplicationBuilder UseLiteXSQLiteCache(this IApplicationBuilder app) { try { SqliteConnection connection = ServiceProviderServiceExtensions.GetService <ISQLiteConnectionProvider>(app.ApplicationServices).GetConnection(); if (((DbConnection)connection).State == ConnectionState.Closed) { ((DbConnection)connection).Open(); } SqlMapper.Execute((IDbConnection)connection, "CREATE TABLE IF NOT EXISTS [litexcache] (\r\n [ID] INTEGER PRIMARY KEY\r\n , [cachekey] TEXT\r\n , [cachevalue] TEXT\r\n , [expiration] INTEGER)", (object)null, (IDbTransaction)null, (int?)null, (CommandType?)null); return(app); } catch (Exception ex) { Console.WriteLine(ex.Message); return(app); } }
private void ConfigureTenantPipeline(IApplicationBuilder appBuilder) { V_0 = new ModularTenantRouterMiddleware.u003cu003ec__DisplayClass7_0(); V_0.appBuilder = appBuilder; V_0.startups = ServiceProviderServiceExtensions.GetServices <IStartup>(V_0.appBuilder.get_ApplicationServices()); stackVariable8 = V_0; stackVariable10 = V_0.startups; stackVariable11 = ModularTenantRouterMiddleware.u003cu003ec.u003cu003e9__7_0; if (stackVariable11 == null) { dummyVar0 = stackVariable11; stackVariable11 = new Func <IStartup, int>(ModularTenantRouterMiddleware.u003cu003ec.u003cu003e9.u003cConfigureTenantPipelineu003eb__7_0); ModularTenantRouterMiddleware.u003cu003ec.u003cu003e9__7_0 = stackVariable11; } stackVariable8.startups = stackVariable10.OrderBy <IStartup, int>(stackVariable11); dummyVar1 = EndpointRoutingApplicationBuilderExtensions.UseEndpoints(EndpointRoutingApplicationBuilderExtensions.UseRouting(V_0.appBuilder), new Action <IEndpointRouteBuilder>(V_0.u003cConfigureTenantPipelineu003eb__1)); return; }
public static void EnsurePopulated(IApplicationBuilder app) { AirportContext context = ServiceProviderServiceExtensions.GetRequiredService <AirportContext>(app.ApplicationServices); context.Database.EnsureCreated(); if (!context.Tickets.Any()) { context.Tickets.AddRange( new Ticket() { Id = 1, Price = 1M, FlightNumber = "", }, new Ticket() { Id = 2, Price = 1M, FlightNumber = "", } ); context.SaveChanges(); } if (!context.PlaneTypes.Any()) { context.PlaneTypes.AddRange( new PlaneType() { Id = 1, Model = "AN", Seats = 100, }, new PlaneType() { Id = 2, Model = "AN", Seats = 200, } ); context.SaveChanges(); } }
/// <summary> /// 记录异常日志。 /// </summary> /// <param name="filterContext"></param> protected virtual void LogException(ExceptionContext filterContext) { var controllerName = (string)filterContext.RouteData.Values["controller"]; var actionName = (string)filterContext.RouteData.Values["action"]; Tracer.Error($"Throw exception when '{controllerName}.{actionName}' is executed:\n{filterContext.Exception.Output()}"); //记录日志 #if !NETCOREAPP var logger = LoggerFactory.CreateLogger(); #else var logger = ServiceProviderServiceExtensions.GetService <ILogger>(filterContext.HttpContext.RequestServices); #endif if (logger != null) { logger.Error(string.Format("执行控制器 {0} 的方法 {1} 时发生错误。", controllerName, actionName), filterContext.Exception); } }
public static void UseStaticCommands(this IAppBuilder builder, StaticCommandsList staticCommands) { builder.UsePossibleCommands(); builder.Services.TryAddSingleton(provider => { ServiceProviderServiceExtensions.GetService <ILogger>(provider) ?.Debug("Loaded {Count} static commands: {Commands}", staticCommands.StaticCommandsTypes.Count, string.Join(", ", staticCommands.StaticCommandsTypes.Select(a => a.Name))); return(staticCommands); }); builder.UseMiddleware <StaticCommandsMiddleware>(); foreach (var command in staticCommands.StaticCommandsTypes) { builder.Services.AddScoped(command); } }
public override void OnApplicationInitialization(ApplicationInitializationContext context) { var app = context.GetApplicationBuilder(); var env = ServiceProviderServiceExtensions.GetRequiredService <IWebHostEnvironment>(context.ServiceProvider); NLog.LogManager.LoadConfiguration("nlog.config").GetCurrentClassLogger(); NLog.LogManager.Configuration.Variables["connectionString"] = context.Configuration["ConnectionStrings:MySql"]; Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); //避免日志中的中文输出乱码 // 环境变量,开发环境 if (env.IsDevelopment()) { // 生成异常页面 app.UseDeveloperExceptionPage(); } // 使用HSTS的中间件,该中间件添加了严格传输安全头 app.UseHsts(); // 转发将标头代理到当前请求,配合 Nginx 使用,获取用户真实IP app.UseForwardedHeaders(new ForwardedHeadersOptions { ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto }); // 跨域 app.UseCors(p => p.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod()); // 异常处理中间件 //app.UseMiddleware<ExceptionHandlerMiddleware>(); app.UseSwaggerMiddle(); // HTTP => HTTPS app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); // 路由映射 app.UseEndpoints(endpoints => { //全局路由配置 endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}" ); }); }
public static IApplicationBuilder UseOrchardCore(this IApplicationBuilder app, Action <IApplicationBuilder> configure = null) { V_0 = ServiceProviderServiceExtensions.GetRequiredService <IHostEnvironment>(app.get_ApplicationServices()); V_1 = ServiceProviderServiceExtensions.GetRequiredService <IApplicationContext>(app.get_ApplicationServices()); stackVariable8 = new IFileProvider[2]; stackVariable8[0] = new ModuleEmbeddedFileProvider(V_1); stackVariable8[1] = V_0.get_ContentRootFileProvider(); V_0.set_ContentRootFileProvider(new CompositeFileProvider(stackVariable8)); ServiceProviderServiceExtensions.GetRequiredService <IWebHostEnvironment>(app.get_ApplicationServices()).set_ContentRootFileProvider(V_0.get_ContentRootFileProvider()); dummyVar0 = UseMiddlewareExtensions.UseMiddleware <PoweredByMiddleware>(app, Array.Empty <object>()); dummyVar1 = UseMiddlewareExtensions.UseMiddleware <ModularTenantContainerMiddleware>(app, Array.Empty <object>()); if (configure != null) { configure.Invoke(app); } stackVariable30 = new object[1]; stackVariable30[0] = app.get_ServerFeatures(); dummyVar2 = UseMiddlewareExtensions.UseMiddleware <ModularTenantRouterMiddleware>(app, stackVariable30); return(app); }
private static ODataRoute MapDynamicODataServiceRoute(this IRouteBuilder builder, string routeName, string routePrefix, IODataPathHandler pathHandler, IEnumerable <IODataRoutingConvention> routingConventions, IDataSource dataSource) { ServiceProviderServiceExtensions.GetRequiredService <ApplicationPartManager>(builder.ServiceProvider).ApplicationParts.Add(new AssemblyPart(typeof(DynamicODataController).Assembly)); var odataRoute = builder.MapODataServiceRoute(routeName, routePrefix, containerBuilder => { containerBuilder .AddService <IEdmModel>(Microsoft.OData.ServiceLifetime.Singleton, sp => dataSource.Model) .AddService <IDataSource>(Microsoft.OData.ServiceLifetime.Scoped, sp => dataSource) .AddService(Microsoft.OData.ServiceLifetime.Scoped, sp => routingConventions.ToList().AsEnumerable()); if (pathHandler != null) { containerBuilder.AddService(Microsoft.OData.ServiceLifetime.Singleton, sp => pathHandler); } }); return(odataRoute); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, YsbqcSetting set) { //var rewrite = new RewriteOptions().AddRedirect(@"m2/(\w+)", "?m3=$1"); //app.UseRewriter(rewrite); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); } //MyRewrite(app); var provider = new FileExtensionContentTypeProvider(); provider.Mappings[".jsp"] = "text/html"; app.UseStaticFiles(new StaticFileOptions { ContentTypeProvider = provider }); app.UseCookiePolicy(); app.UseSession(); app.UseMiddleware <SessionMiddleware>(set); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); GTXMethod.config = Configuration; GTXMethod.set = ServiceProviderServiceExtensions.GetRequiredService <YsbqcSetting>(app.ApplicationServices); }