diff --git a/Ocelot.Release.sln b/Ocelot.Release.sln
index 20a76ee83..4460d9ddf 100644
--- a/Ocelot.Release.sln
+++ b/Ocelot.Release.sln
@@ -52,7 +52,7 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Ocelot.Tracing.Butterfly",
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Ocelot.Tracing.OpenTracing", "src\Ocelot.Tracing.OpenTracing\Ocelot.Tracing.OpenTracing.csproj", "{11C622AD-8C0A-4CF4-811B-3DBB76550797}"
EndProject
-Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Samples", "samples", "{8FA0CBA0-0338-48EB-B37F-83CA5022237C}"
+Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Samples", "Samples", "{8FA0CBA0-0338-48EB-B37F-83CA5022237C}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Ocelot.Samples.AdministrationApi", "samples\Administration\Ocelot.Samples.AdministrationApi.csproj", "{A7F0CAFA-AECB-43CA-BE89-5F5B728E7C22}"
EndProject
@@ -78,16 +78,14 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Ocelot.Samples.ServiceFabri
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Ocelot.Samples.ServiceFabric.DownstreamService", "samples\ServiceFabric\DownstreamService\Ocelot.Samples.ServiceFabric.DownstreamService.csproj", "{AD09D124-7DD7-4C9E-9BCC-782B579B1786}"
EndProject
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Ocelot.Samples.Web", "samples\Web\Ocelot.Samples.Web.csproj", "{1A00E87D-2B0B-4D61-A606-3D747C1E43F8}"
+EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
- {D6DF4206-0DBA-41D8-884D-C3E08290FDBB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {D6DF4206-0DBA-41D8-884D-C3E08290FDBB}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {D6DF4206-0DBA-41D8-884D-C3E08290FDBB}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {D6DF4206-0DBA-41D8-884D-C3E08290FDBB}.Release|Any CPU.Build.0 = Release|Any CPU
{54E84F1A-E525-4443-96EC-039CBD50C263}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{54E84F1A-E525-4443-96EC-039CBD50C263}.Debug|Any CPU.Build.0 = Debug|Any CPU
{54E84F1A-E525-4443-96EC-039CBD50C263}.Release|Any CPU.ActiveCfg = Release|Any CPU
@@ -108,6 +106,14 @@ Global
{D4575572-99CA-4530-8737-C296EDA326F8}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D4575572-99CA-4530-8737-C296EDA326F8}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D4575572-99CA-4530-8737-C296EDA326F8}.Release|Any CPU.Build.0 = Release|Any CPU
+ {AE6BCCBD-0687-4C58-B30F-4ABBC6422087}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {AE6BCCBD-0687-4C58-B30F-4ABBC6422087}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {AE6BCCBD-0687-4C58-B30F-4ABBC6422087}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {AE6BCCBD-0687-4C58-B30F-4ABBC6422087}.Release|Any CPU.Build.0 = Release|Any CPU
+ {D6DF4206-0DBA-41D8-884D-C3E08290FDBB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {D6DF4206-0DBA-41D8-884D-C3E08290FDBB}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {D6DF4206-0DBA-41D8-884D-C3E08290FDBB}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {D6DF4206-0DBA-41D8-884D-C3E08290FDBB}.Release|Any CPU.Build.0 = Release|Any CPU
{F69CEF43-27D2-4940-A47A-FCA879E371BC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{F69CEF43-27D2-4940-A47A-FCA879E371BC}.Debug|Any CPU.Build.0 = Debug|Any CPU
{F69CEF43-27D2-4940-A47A-FCA879E371BC}.Release|Any CPU.ActiveCfg = Release|Any CPU
@@ -124,6 +130,10 @@ Global
{9BBD3586-145C-4FA0-91C5-9ED58287D753}.Debug|Any CPU.Build.0 = Debug|Any CPU
{9BBD3586-145C-4FA0-91C5-9ED58287D753}.Release|Any CPU.ActiveCfg = Release|Any CPU
{9BBD3586-145C-4FA0-91C5-9ED58287D753}.Release|Any CPU.Build.0 = Release|Any CPU
+ {72C8E528-B4F5-45CE-8A06-CD3787364856}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {72C8E528-B4F5-45CE-8A06-CD3787364856}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {72C8E528-B4F5-45CE-8A06-CD3787364856}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {72C8E528-B4F5-45CE-8A06-CD3787364856}.Release|Any CPU.Build.0 = Release|Any CPU
{1F6E5DCF-8A2E-4E24-A25D-064362DE8D0E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{1F6E5DCF-8A2E-4E24-A25D-064362DE8D0E}.Debug|Any CPU.Build.0 = Debug|Any CPU
{1F6E5DCF-8A2E-4E24-A25D-064362DE8D0E}.Release|Any CPU.ActiveCfg = Release|Any CPU
@@ -132,18 +142,10 @@ Global
{6045E23D-669C-4F27-AF8E-8EEE6DB3557F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{6045E23D-669C-4F27-AF8E-8EEE6DB3557F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{6045E23D-669C-4F27-AF8E-8EEE6DB3557F}.Release|Any CPU.Build.0 = Release|Any CPU
- {72C8E528-B4F5-45CE-8A06-CD3787364856}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {72C8E528-B4F5-45CE-8A06-CD3787364856}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {72C8E528-B4F5-45CE-8A06-CD3787364856}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {72C8E528-B4F5-45CE-8A06-CD3787364856}.Release|Any CPU.Build.0 = Release|Any CPU
{11C622AD-8C0A-4CF4-811B-3DBB76550797}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{11C622AD-8C0A-4CF4-811B-3DBB76550797}.Debug|Any CPU.Build.0 = Debug|Any CPU
{11C622AD-8C0A-4CF4-811B-3DBB76550797}.Release|Any CPU.ActiveCfg = Release|Any CPU
{11C622AD-8C0A-4CF4-811B-3DBB76550797}.Release|Any CPU.Build.0 = Release|Any CPU
- {AE6BCCBD-0687-4C58-B30F-4ABBC6422087}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {AE6BCCBD-0687-4C58-B30F-4ABBC6422087}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {AE6BCCBD-0687-4C58-B30F-4ABBC6422087}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {AE6BCCBD-0687-4C58-B30F-4ABBC6422087}.Release|Any CPU.Build.0 = Release|Any CPU
{A7F0CAFA-AECB-43CA-BE89-5F5B728E7C22}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{A7F0CAFA-AECB-43CA-BE89-5F5B728E7C22}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A7F0CAFA-AECB-43CA-BE89-5F5B728E7C22}.Release|Any CPU.ActiveCfg = Release|Any CPU
@@ -192,26 +194,30 @@ Global
{AD09D124-7DD7-4C9E-9BCC-782B579B1786}.Debug|Any CPU.Build.0 = Debug|Any CPU
{AD09D124-7DD7-4C9E-9BCC-782B579B1786}.Release|Any CPU.ActiveCfg = Release|Any CPU
{AD09D124-7DD7-4C9E-9BCC-782B579B1786}.Release|Any CPU.Build.0 = Release|Any CPU
+ {1A00E87D-2B0B-4D61-A606-3D747C1E43F8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {1A00E87D-2B0B-4D61-A606-3D747C1E43F8}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {1A00E87D-2B0B-4D61-A606-3D747C1E43F8}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {1A00E87D-2B0B-4D61-A606-3D747C1E43F8}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
- {D6DF4206-0DBA-41D8-884D-C3E08290FDBB} = {5CFB79B7-C9DC-45A4-9A75-625D92471702}
{54E84F1A-E525-4443-96EC-039CBD50C263} = {5B401523-36DA-4491-B73A-7590A26E420B}
{F8C224FE-36BE-45F5-9B0E-666D8F4A9B52} = {5B401523-36DA-4491-B73A-7590A26E420B}
{02BBF4C5-517E-4157-8D21-4B8B9E118B7A} = {5B401523-36DA-4491-B73A-7590A26E420B}
{106B49E6-95F6-4A7B-B81C-96BFA74AF035} = {5B401523-36DA-4491-B73A-7590A26E420B}
{D4575572-99CA-4530-8737-C296EDA326F8} = {5B401523-36DA-4491-B73A-7590A26E420B}
+ {AE6BCCBD-0687-4C58-B30F-4ABBC6422087} = {5B401523-36DA-4491-B73A-7590A26E420B}
+ {D6DF4206-0DBA-41D8-884D-C3E08290FDBB} = {5CFB79B7-C9DC-45A4-9A75-625D92471702}
{F69CEF43-27D2-4940-A47A-FCA879E371BC} = {5CFB79B7-C9DC-45A4-9A75-625D92471702}
{EB9F438F-062E-499F-B6EA-4412BEF6D74C} = {5CFB79B7-C9DC-45A4-9A75-625D92471702}
{02F5AE4D-9C36-4E58-B7C6-012CBBDEFDE0} = {5CFB79B7-C9DC-45A4-9A75-625D92471702}
{9BBD3586-145C-4FA0-91C5-9ED58287D753} = {5CFB79B7-C9DC-45A4-9A75-625D92471702}
+ {72C8E528-B4F5-45CE-8A06-CD3787364856} = {5CFB79B7-C9DC-45A4-9A75-625D92471702}
{1F6E5DCF-8A2E-4E24-A25D-064362DE8D0E} = {5CFB79B7-C9DC-45A4-9A75-625D92471702}
{6045E23D-669C-4F27-AF8E-8EEE6DB3557F} = {5CFB79B7-C9DC-45A4-9A75-625D92471702}
- {72C8E528-B4F5-45CE-8A06-CD3787364856} = {5CFB79B7-C9DC-45A4-9A75-625D92471702}
{11C622AD-8C0A-4CF4-811B-3DBB76550797} = {5CFB79B7-C9DC-45A4-9A75-625D92471702}
- {AE6BCCBD-0687-4C58-B30F-4ABBC6422087} = {5B401523-36DA-4491-B73A-7590A26E420B}
{A7F0CAFA-AECB-43CA-BE89-5F5B728E7C22} = {8FA0CBA0-0338-48EB-B37F-83CA5022237C}
{F00C73F4-019D-490D-8194-CA1754D717FA} = {8FA0CBA0-0338-48EB-B37F-83CA5022237C}
{FECB0C8B-5778-4441-B10E-0C815F5106D5} = {8FA0CBA0-0338-48EB-B37F-83CA5022237C}
@@ -224,6 +230,7 @@ Global
{DCBD0AB5-85DD-4F28-9166-0A23969E19EC} = {8FA0CBA0-0338-48EB-B37F-83CA5022237C}
{D991C694-01F0-4F04-8135-5C133DC8E029} = {8FA0CBA0-0338-48EB-B37F-83CA5022237C}
{AD09D124-7DD7-4C9E-9BCC-782B579B1786} = {8FA0CBA0-0338-48EB-B37F-83CA5022237C}
+ {1A00E87D-2B0B-4D61-A606-3D747C1E43F8} = {8FA0CBA0-0338-48EB-B37F-83CA5022237C}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {21476EFF-778A-4F97-8A56-D1AF1CEC0C48}
diff --git a/samples/Administration/Ocelot.Samples.AdministrationApi.csproj b/samples/Administration/Ocelot.Samples.AdministrationApi.csproj
index cd995c774..943273aed 100644
--- a/samples/Administration/Ocelot.Samples.AdministrationApi.csproj
+++ b/samples/Administration/Ocelot.Samples.AdministrationApi.csproj
@@ -1,14 +1,12 @@
- net6.0;net7.0;net8.0
+ net8.0
disable
disable
-
-
-
+
diff --git a/samples/Administration/Program.cs b/samples/Administration/Program.cs
index 5359a9a73..8753948c6 100644
--- a/samples/Administration/Program.cs
+++ b/samples/Administration/Program.cs
@@ -4,43 +4,40 @@
using Ocelot.Administration;
using Ocelot.DependencyInjection;
using Ocelot.Middleware;
-using System.IO;
+using Ocelot.Samples.Web;
-namespace AdministrationApi
+namespace AdministrationApi;
+
+public class Program
{
- public class Program
+ public static void Main(string[] args)
{
- public static void Main(string[] args)
- {
- new WebHostBuilder()
- .UseKestrel()
- .UseUrls("http://localhost:5000")
- .UseContentRoot(Directory.GetCurrentDirectory())
- .ConfigureAppConfiguration((hostingContext, config) =>
- {
- config
- .SetBasePath(hostingContext.HostingEnvironment.ContentRootPath)
- .AddJsonFile("appsettings.json", true, true)
- .AddJsonFile($"appsettings.{hostingContext.HostingEnvironment.EnvironmentName}.json", true, true)
- .AddJsonFile("ocelot.json")
- .AddEnvironmentVariables();
- })
- .ConfigureServices(s =>
- {
- s.AddOcelot()
- .AddAdministration("/administration", "secret");
- })
- .ConfigureLogging((hostingContext, logging) =>
- {
- logging.AddConsole();
- })
- .UseIISIntegration()
- .Configure(app =>
- {
- app.UseOcelot().Wait();
- })
- .Build()
- .Run();
- }
+ OcelotHostBuilder.Create(args)
+ .UseUrls("http://localhost:5000")
+ .ConfigureAppConfiguration((hostingContext, config) =>
+ {
+ config
+ .SetBasePath(hostingContext.HostingEnvironment.ContentRootPath)
+ .AddJsonFile("appsettings.json", true, true)
+ .AddJsonFile($"appsettings.{hostingContext.HostingEnvironment.EnvironmentName}.json", true, true)
+ .AddJsonFile("ocelot.json")
+ .AddEnvironmentVariables();
+ })
+ .ConfigureServices(s =>
+ {
+ s.AddOcelot()
+ .AddAdministration("/administration", "secret");
+ })
+ .ConfigureLogging((hostingContext, logging) =>
+ {
+ logging.AddConsole();
+ })
+ .UseIISIntegration()
+ .Configure(app =>
+ {
+ app.UseOcelot().Wait();
+ })
+ .Build()
+ .Run();
}
}
diff --git a/samples/Basic/Ocelot.Samples.Basic.ApiGateway.csproj b/samples/Basic/Ocelot.Samples.Basic.ApiGateway.csproj
index 9e381bb17..c4209a428 100644
--- a/samples/Basic/Ocelot.Samples.Basic.ApiGateway.csproj
+++ b/samples/Basic/Ocelot.Samples.Basic.ApiGateway.csproj
@@ -1,6 +1,6 @@
- net6.0;net7.0;net8.0
+ net8.0
disable
disable
InProcess
@@ -10,5 +10,6 @@
+
diff --git a/samples/Basic/Program.cs b/samples/Basic/Program.cs
index 3901407c2..876ee7e07 100644
--- a/samples/Basic/Program.cs
+++ b/samples/Basic/Program.cs
@@ -3,7 +3,7 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
-using System.IO;
+using Ocelot.Samples.Web;
namespace Ocelot.Samples.OcelotBasic.ApiGateway;
@@ -11,9 +11,7 @@ public class Program
{
public static void Main(string[] args)
{
- new WebHostBuilder()
- .UseKestrel()
- .UseContentRoot(Directory.GetCurrentDirectory())
+ OcelotHostBuilder.BasicSetup()
.ConfigureAppConfiguration((hostingContext, config) =>
{
config
diff --git a/samples/Eureka/ApiGateway/Ocelot.Samples.Eureka.ApiGateway.csproj b/samples/Eureka/ApiGateway/Ocelot.Samples.Eureka.ApiGateway.csproj
index a41f67537..190682c29 100644
--- a/samples/Eureka/ApiGateway/Ocelot.Samples.Eureka.ApiGateway.csproj
+++ b/samples/Eureka/ApiGateway/Ocelot.Samples.Eureka.ApiGateway.csproj
@@ -1,6 +1,6 @@
- net6.0;net7.0;net8.0
+ net8.0
disable
disable
@@ -16,5 +16,6 @@
+
diff --git a/samples/Eureka/ApiGateway/Program.cs b/samples/Eureka/ApiGateway/Program.cs
index 1a76b760d..0c0674dd2 100644
--- a/samples/Eureka/ApiGateway/Program.cs
+++ b/samples/Eureka/ApiGateway/Program.cs
@@ -1,42 +1,39 @@
-using Microsoft.AspNetCore;
-using Microsoft.AspNetCore.Hosting;
+using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Ocelot.DependencyInjection;
using Ocelot.Middleware;
using Ocelot.Provider.Eureka;
using Ocelot.Provider.Polly;
+using Ocelot.Samples.Web;
-namespace ApiGateway
+namespace ApiGateway;
+
+public class Program
{
- public class Program
+ public static void Main(string[] args)
{
- public static void Main(string[] args)
- {
- BuildWebHost(args).Run();
- }
-
- public static IWebHost BuildWebHost(string[] args) =>
- WebHost.CreateDefaultBuilder(args)
- .UseUrls("http://localhost:5000")
- .ConfigureAppConfiguration((hostingContext, config) =>
- {
- config
- .SetBasePath(hostingContext.HostingEnvironment.ContentRootPath)
- .AddJsonFile("appsettings.json", true, true)
- .AddJsonFile($"appsettings.{hostingContext.HostingEnvironment.EnvironmentName}.json", true, true)
- .AddJsonFile("ocelot.json", false, false)
- .AddEnvironmentVariables();
- })
- .ConfigureServices(s =>
- {
- s.AddOcelot()
- .AddEureka()
- .AddPolly();
- })
- .Configure(a =>
- {
- a.UseOcelot().Wait();
- })
- .Build();
+ OcelotHostBuilder.Create(args)
+ .UseUrls("http://localhost:5000")
+ .ConfigureAppConfiguration((hostingContext, config) =>
+ {
+ config
+ .SetBasePath(hostingContext.HostingEnvironment.ContentRootPath)
+ .AddJsonFile("appsettings.json", true, true)
+ .AddJsonFile($"appsettings.{hostingContext.HostingEnvironment.EnvironmentName}.json", true, true)
+ .AddJsonFile("ocelot.json", false, false)
+ .AddEnvironmentVariables();
+ })
+ .ConfigureServices(s =>
+ {
+ s.AddOcelot()
+ .AddEureka()
+ .AddPolly();
+ })
+ .Configure(a =>
+ {
+ a.UseOcelot().Wait();
+ })
+ .Build()
+ .Run();
}
}
diff --git a/samples/Eureka/DownstreamService/Ocelot.Samples.Eureka.DownstreamService.csproj b/samples/Eureka/DownstreamService/Ocelot.Samples.Eureka.DownstreamService.csproj
index e0d47d1c9..652d0131d 100644
--- a/samples/Eureka/DownstreamService/Ocelot.Samples.Eureka.DownstreamService.csproj
+++ b/samples/Eureka/DownstreamService/Ocelot.Samples.Eureka.DownstreamService.csproj
@@ -1,16 +1,16 @@
- net6.0;net7.0;net8.0
+ net8.0
disable
disable
-
-
-
+
+
+
diff --git a/samples/Eureka/DownstreamService/Program.cs b/samples/Eureka/DownstreamService/Program.cs
index dbba1be26..6a26dc83c 100644
--- a/samples/Eureka/DownstreamService/Program.cs
+++ b/samples/Eureka/DownstreamService/Program.cs
@@ -1,20 +1,19 @@
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
+using Ocelot.Samples.Web;
using System;
-namespace DownstreamService
+namespace DownstreamService;
+
+public class Program
{
- public class Program
+ public static void Main(string[] args)
{
- public static void Main(string[] args)
- {
- BuildWebHost(args).Run();
- }
-
- public static IWebHost BuildWebHost(string[] args) =>
- WebHost.CreateDefaultBuilder(args)
- .UseUrls($"http://{Environment.MachineName}:5001")
- .UseStartup()
- .Build();
+ DownstreamHostBuilder.Create(args)
+ .UseUrls($"http://{Environment.MachineName}:5001")
+ .UseStartup()
+ .Build()
+ .Run();
}
+
}
diff --git a/samples/GraphQL/Ocelot.Samples.GraphQL.csproj b/samples/GraphQL/Ocelot.Samples.GraphQL.csproj
index 32039beba..5f504b99b 100644
--- a/samples/GraphQL/Ocelot.Samples.GraphQL.csproj
+++ b/samples/GraphQL/Ocelot.Samples.GraphQL.csproj
@@ -1,6 +1,6 @@
- net6.0;net7.0;net8.0
+ net8.0
disable
disable
@@ -17,5 +17,6 @@
+
diff --git a/samples/GraphQL/Program.cs b/samples/GraphQL/Program.cs
index e2f19aaaf..8393122f6 100644
--- a/samples/GraphQL/Program.cs
+++ b/samples/GraphQL/Program.cs
@@ -6,86 +6,86 @@
using Microsoft.Extensions.Logging;
using Ocelot.DependencyInjection;
using Ocelot.Middleware;
+using Ocelot.Samples.Web;
using System.Collections.Generic;
-using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
-namespace OcelotGraphQL
+namespace OcelotGraphQL;
+
+public class Hero
+{
+ public int Id { get; set; }
+ public string Name { get; set; }
+}
+
+public class Query
{
- public class Hero
+ private readonly List _heroes = new()
{
- public int Id { get; set; }
- public string Name { get; set; }
- }
+ new Hero { Id = 1, Name = "R2-D2" },
+ new Hero { Id = 2, Name = "Batman" },
+ new Hero { Id = 3, Name = "Wonder Woman" },
+ new Hero { Id = 4, Name = "Tom Pallister" }
+ };
- public class Query
+ [GraphQLMetadata("hero")]
+ public Hero GetHero(int id)
{
- private readonly List _heroes = new()
- {
- new Hero { Id = 1, Name = "R2-D2" },
- new Hero { Id = 2, Name = "Batman" },
- new Hero { Id = 3, Name = "Wonder Woman" },
- new Hero { Id = 4, Name = "Tom Pallister" }
- };
+ return _heroes.FirstOrDefault(x => x.Id == id);
+ }
+}
- [GraphQLMetadata("hero")]
- public Hero GetHero(int id)
- {
- return _heroes.FirstOrDefault(x => x.Id == id);
- }
+public class GraphQlDelegatingHandler : DelegatingHandler
+{
+ //private readonly ISchema _schema;
+ private readonly IDocumentExecuter _executer;
+ private readonly IDocumentWriter _writer;
+
+ public GraphQlDelegatingHandler(IDocumentExecuter executer, IDocumentWriter writer)
+ {
+ _executer = executer;
+ _writer = writer;
}
- public class GraphQlDelegatingHandler : DelegatingHandler
+ protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
- //private readonly ISchema _schema;
- private readonly IDocumentExecuter _executer;
- private readonly IDocumentWriter _writer;
+ //try get query from body, could check http method :)
+ var query = await request.Content.ReadAsStringAsync(cancellationToken);
- public GraphQlDelegatingHandler(IDocumentExecuter executer, IDocumentWriter writer)
+ //if not body try query string, dont hack like this in real world..
+ if (query.Length == 0)
{
- _executer = executer;
- _writer = writer;
+ var decoded = WebUtility.UrlDecode(request.RequestUri.Query);
+ query = decoded.Replace("?query=", string.Empty);
}
- protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
+ var result = await _executer.ExecuteAsync(_ =>
{
- //try get query from body, could check http method :)
- var query = await request.Content.ReadAsStringAsync(cancellationToken);
-
- //if not body try query string, dont hack like this in real world..
- if (query.Length == 0)
- {
- var decoded = WebUtility.UrlDecode(request.RequestUri.Query);
- query = decoded.Replace("?query=", string.Empty);
- }
+ _.Query = query;
+ });
- var result = await _executer.ExecuteAsync(_ =>
- {
- _.Query = query;
- });
-
- var responseBody = await _writer.WriteToStringAsync(result);
+ var responseBody = await _writer.WriteToStringAsync(result);
- //maybe check for errors and headers etc in real world?
- var response = new HttpResponseMessage(HttpStatusCode.OK)
- {
- Content = new StringContent(responseBody)
- };
+ //maybe check for errors and headers etc in real world?
+ var response = new HttpResponseMessage(HttpStatusCode.OK)
+ {
+ Content = new StringContent(responseBody)
+ };
- //ocelot will treat this like any other http request...
- return response;
- }
+ //ocelot will treat this like any other http request...
+ return response;
}
+}
- public class Program
+public class Program
+{
+ public static void Main(string[] args)
{
- public static void Main()
- {
- var schema = Schema.For(@"
+ var schema = Schema.For(@"
type Hero {
id: Int
name: String
@@ -95,40 +95,37 @@ type Query {
hero(id: Int): Hero
}
", _ =>
- {
- _.Types.Include();
- });
+ {
+ _.Types.Include();
+ });
- new WebHostBuilder()
- .UseKestrel()
- .UseContentRoot(Directory.GetCurrentDirectory())
- .ConfigureAppConfiguration((hostingContext, config) =>
- {
- config
- .SetBasePath(hostingContext.HostingEnvironment.ContentRootPath)
- .AddJsonFile("appsettings.json", true, true)
- .AddJsonFile($"appsettings.{hostingContext.HostingEnvironment.EnvironmentName}.json", true, true)
- .AddJsonFile("ocelot.json", false, false)
- .AddEnvironmentVariables();
- })
- .ConfigureServices(s =>
- {
- s.AddSingleton(schema);
- s.AddOcelot()
- .AddDelegatingHandler();
- })
- .ConfigureLogging((hostingContext, logging) =>
- {
- logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
- logging.AddConsole();
- })
- .UseIISIntegration()
- .Configure(app =>
- {
- app.UseOcelot().Wait();
- })
- .Build()
- .Run();
- }
+ OcelotHostBuilder.Create(args)
+ .ConfigureAppConfiguration((hostingContext, config) =>
+ {
+ config
+ .SetBasePath(hostingContext.HostingEnvironment.ContentRootPath)
+ .AddJsonFile("appsettings.json", true, true)
+ .AddJsonFile($"appsettings.{hostingContext.HostingEnvironment.EnvironmentName}.json", true, true)
+ .AddJsonFile("ocelot.json", false, false)
+ .AddEnvironmentVariables();
+ })
+ .ConfigureServices(s =>
+ {
+ s.AddSingleton(schema);
+ s.AddOcelot()
+ .AddDelegatingHandler();
+ })
+ .ConfigureLogging((hostingContext, logging) =>
+ {
+ logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
+ logging.AddConsole();
+ })
+ .UseIISIntegration()
+ .Configure(app =>
+ {
+ app.UseOcelot().Wait();
+ })
+ .Build()
+ .Run();
}
}
diff --git a/samples/Kubernetes/ApiGateway/Ocelot.Samples.Kubernetes.ApiGateway.csproj b/samples/Kubernetes/ApiGateway/Ocelot.Samples.Kubernetes.ApiGateway.csproj
index e62d4e98b..8da9d01d8 100644
--- a/samples/Kubernetes/ApiGateway/Ocelot.Samples.Kubernetes.ApiGateway.csproj
+++ b/samples/Kubernetes/ApiGateway/Ocelot.Samples.Kubernetes.ApiGateway.csproj
@@ -1,6 +1,6 @@
- net6.0;net7.0;net8.0
+ net8.0
disable
disable
InProcess
@@ -9,5 +9,6 @@
+
diff --git a/samples/Kubernetes/ApiGateway/Program.cs b/samples/Kubernetes/ApiGateway/Program.cs
index 36f5fe49c..a620289fc 100644
--- a/samples/Kubernetes/ApiGateway/Program.cs
+++ b/samples/Kubernetes/ApiGateway/Program.cs
@@ -1,6 +1,6 @@
-using Microsoft.AspNetCore;
-using Microsoft.AspNetCore.Hosting;
+using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
+using Ocelot.Samples.Web;
namespace Ocelot.Samples.OcelotKube.ApiGateway;
@@ -8,11 +8,7 @@ public class Program
{
public static void Main(string[] args)
{
- BuildWebHost(args).Run();
- }
-
- public static IWebHost BuildWebHost(string[] args) =>
- WebHost.CreateDefaultBuilder(args)
+ OcelotHostBuilder.Create(args)
.ConfigureAppConfiguration((hostingContext, config) =>
{
config
@@ -23,5 +19,7 @@ public static IWebHost BuildWebHost(string[] args) =>
.AddEnvironmentVariables();
})
.UseStartup()
- .Build();
+ .Build()
+ .Run();
+ }
}
diff --git a/samples/Kubernetes/DownstreamService/Ocelot.Samples.Kubernetes.DownstreamService.csproj b/samples/Kubernetes/DownstreamService/Ocelot.Samples.Kubernetes.DownstreamService.csproj
index 72b36b2fc..d54d6de9f 100644
--- a/samples/Kubernetes/DownstreamService/Ocelot.Samples.Kubernetes.DownstreamService.csproj
+++ b/samples/Kubernetes/DownstreamService/Ocelot.Samples.Kubernetes.DownstreamService.csproj
@@ -1,6 +1,6 @@
- net6.0;net7.0;net8.0
+ net8.0
disable
disable
InProcess
@@ -9,4 +9,7 @@
+
+
+
diff --git a/samples/Kubernetes/DownstreamService/Program.cs b/samples/Kubernetes/DownstreamService/Program.cs
index 94f139c01..42d8b0392 100644
--- a/samples/Kubernetes/DownstreamService/Program.cs
+++ b/samples/Kubernetes/DownstreamService/Program.cs
@@ -2,6 +2,7 @@
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
+using Ocelot.Samples.Web;
using System.Text.Json;
using System.Text.Json.Serialization;
@@ -11,6 +12,7 @@ public class Program
{
public static void Main(string[] args)
{
+ //var builder = DownstreamHostBuilder.Create(args);
var builder = WebApplication.CreateBuilder(args);
builder.Services
diff --git a/samples/Ocelot.Samples.sln b/samples/Ocelot.Samples.sln
index ca208f4a6..93aeba9c6 100644
--- a/samples/Ocelot.Samples.sln
+++ b/samples/Ocelot.Samples.sln
@@ -3,6 +3,8 @@ Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.9.34728.123
MinimumVisualStudioVersion = 10.0.40219.1
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Ocelot", "..\src\Ocelot\Ocelot.csproj", "{B37314F1-C1B5-4D38-8000-E6E96C0CBD30}"
+EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Ocelot.Samples.AdministrationApi", "Administration\Ocelot.Samples.AdministrationApi.csproj", "{238467FE-19EE-4102-9AF7-51EB2C6F0354}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Ocelot.Samples.Basic.ApiGateway", "Basic\Ocelot.Samples.Basic.ApiGateway.csproj", "{A7D2C43A-E35C-4A89-AEE5-5C87052ECD89}"
@@ -27,6 +29,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Ocelot.Samples.ServiceFabri
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Ocelot.Samples.ServiceFabric.DownstreamService", "ServiceFabric\DownstreamService\Ocelot.Samples.ServiceFabric.DownstreamService.csproj", "{6C777A20-F557-45CF-B87B-11E3C6B29A36}"
EndProject
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Ocelot.Samples.Web", "Web\Ocelot.Samples.Web.csproj", "{EA553F5C-4B94-4E4A-8C3E-0124C5EA5F6E}"
+EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@@ -81,6 +85,14 @@ Global
{6C777A20-F557-45CF-B87B-11E3C6B29A36}.Debug|Any CPU.Build.0 = Debug|Any CPU
{6C777A20-F557-45CF-B87B-11E3C6B29A36}.Release|Any CPU.ActiveCfg = Release|Any CPU
{6C777A20-F557-45CF-B87B-11E3C6B29A36}.Release|Any CPU.Build.0 = Release|Any CPU
+ {B37314F1-C1B5-4D38-8000-E6E96C0CBD30}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {B37314F1-C1B5-4D38-8000-E6E96C0CBD30}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {B37314F1-C1B5-4D38-8000-E6E96C0CBD30}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {B37314F1-C1B5-4D38-8000-E6E96C0CBD30}.Release|Any CPU.Build.0 = Release|Any CPU
+ {EA553F5C-4B94-4E4A-8C3E-0124C5EA5F6E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {EA553F5C-4B94-4E4A-8C3E-0124C5EA5F6E}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {EA553F5C-4B94-4E4A-8C3E-0124C5EA5F6E}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {EA553F5C-4B94-4E4A-8C3E-0124C5EA5F6E}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
diff --git a/samples/OpenTracing/Ocelot.Samples.OpenTracing.csproj b/samples/OpenTracing/Ocelot.Samples.OpenTracing.csproj
index a6733a358..b2a2c38bd 100644
--- a/samples/OpenTracing/Ocelot.Samples.OpenTracing.csproj
+++ b/samples/OpenTracing/Ocelot.Samples.OpenTracing.csproj
@@ -1,7 +1,7 @@
Exe
- net6.0;net7.0;net8.0
+ net8.0
disable
disable
@@ -11,6 +11,7 @@
+
@@ -22,7 +23,7 @@
-
+
diff --git a/samples/OpenTracing/Program.cs b/samples/OpenTracing/Program.cs
index 210f12b04..829c4e33f 100644
--- a/samples/OpenTracing/Program.cs
+++ b/samples/OpenTracing/Program.cs
@@ -6,59 +6,50 @@
using Microsoft.Extensions.Logging;
using Ocelot.DependencyInjection;
using Ocelot.Middleware;
+using Ocelot.Samples.Web;
using Ocelot.Tracing.OpenTracing;
using OpenTracing.Util;
using System.IO;
-namespace OcelotOpenTracing
+namespace Ocelot.Samples.OpenTracing;
+
+public static class Program
{
- internal static class Program
+ public static void Main(string[] args)
{
- private static void Main(string[] args)
- {
- Host.CreateDefaultBuilder()
- .ConfigureWebHostDefaults(webBuilder =>
+ OcelotHostBuilder.Create(args)
+ .ConfigureAppConfiguration((hostingContext, config) =>
+ {
+ config
+ .SetBasePath(hostingContext.HostingEnvironment.ContentRootPath)
+ .AddJsonFile("appsettings.json", optional: false, reloadOnChange: false)
+ .AddJsonFile($"appsettings.{hostingContext.HostingEnvironment.EnvironmentName}.json",
+ optional: true, reloadOnChange: false)
+ .AddJsonFile("ocelot.json", optional: false, reloadOnChange: true)
+ .AddEnvironmentVariables();
+ })
+ .ConfigureServices((context, services) =>
+ {
+ services.AddSingleton(sp =>
{
- webBuilder
- .UseContentRoot(Directory.GetCurrentDirectory())
- .UseKestrel()
- .ConfigureAppConfiguration((hostingContext, config) =>
- {
- config
- .SetBasePath(hostingContext.HostingEnvironment.ContentRootPath)
- .AddJsonFile("appsettings.json", optional: false, reloadOnChange: false)
- .AddJsonFile($"appsettings.{hostingContext.HostingEnvironment.EnvironmentName}.json",
- optional: true, reloadOnChange: false)
- .AddJsonFile("ocelot.json", optional: false, reloadOnChange: true)
- .AddEnvironmentVariables();
- })
- .ConfigureServices((context, services) =>
- {
- services.AddSingleton(sp =>
- {
- var loggerFactory = sp.GetService();
- var config = new Configuration(context.HostingEnvironment.ApplicationName, loggerFactory);
-
- var tracer = config.GetTracer();
- GlobalTracer.Register(tracer);
- return tracer;
- });
-
- services
- .AddOcelot()
- .AddOpenTracing();
- })
- .ConfigureLogging(logging =>
- {
- logging.AddConsole();
- })
- .Configure(app =>
- {
- app.UseOcelot().Wait();
- });
+ var loggerFactory = sp.GetService();
+ var config = new Jaeger.Configuration(context.HostingEnvironment.ApplicationName, loggerFactory);
+ var tracer = config.GetTracer();
+ GlobalTracer.Register(tracer);
+ return tracer;
})
- .Build()
- .Run();
- }
+ .AddOcelot()
+ .AddOpenTracing();
+ })
+ .ConfigureLogging(logging =>
+ {
+ logging.AddConsole();
+ })
+ .Configure(async app =>
+ {
+ await app.UseOcelot();
+ })
+ .Build()
+ .Run();
}
}
diff --git a/samples/ServiceDiscovery/ApiGateway/Ocelot.Samples.ServiceDiscovery.ApiGateway.csproj b/samples/ServiceDiscovery/ApiGateway/Ocelot.Samples.ServiceDiscovery.ApiGateway.csproj
index 815c793e9..3fe5c39cb 100644
--- a/samples/ServiceDiscovery/ApiGateway/Ocelot.Samples.ServiceDiscovery.ApiGateway.csproj
+++ b/samples/ServiceDiscovery/ApiGateway/Ocelot.Samples.ServiceDiscovery.ApiGateway.csproj
@@ -6,5 +6,6 @@
+
diff --git a/samples/ServiceDiscovery/ApiGateway/Program.cs b/samples/ServiceDiscovery/ApiGateway/Program.cs
index 1a0e37336..143c223b5 100644
--- a/samples/ServiceDiscovery/ApiGateway/Program.cs
+++ b/samples/ServiceDiscovery/ApiGateway/Program.cs
@@ -1,10 +1,10 @@
-using Microsoft.AspNetCore;
-using Microsoft.AspNetCore.Hosting;
+using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Ocelot.DependencyInjection;
using Ocelot.Middleware;
+using Ocelot.Samples.Web;
using Ocelot.ServiceDiscovery;
namespace Ocelot.Samples.ServiceDiscovery.ApiGateway;
@@ -15,49 +15,47 @@ public class Program
{
public static void Main(string[] args)
{
- BuildWebHost(args).Run();
- }
+ OcelotHostBuilder.Create(args)
+ .ConfigureAppConfiguration((hostingContext, config) =>
+ {
+ config
+ .SetBasePath(hostingContext.HostingEnvironment.ContentRootPath)
+ .AddJsonFile("appsettings.json", true, true)
+ .AddJsonFile($"appsettings.{hostingContext.HostingEnvironment.EnvironmentName}.json", true, true)
+ .AddJsonFile("ocelot.json", false, false)
+ .AddEnvironmentVariables();
+ })
+ .ConfigureServices(s =>
+ {
+ // Initialize from app configuration or hardcode/choose the best option.
+ bool easyWay = true;
- public static IWebHost BuildWebHost(string[] args) =>
- WebHost.CreateDefaultBuilder(args)
- .ConfigureAppConfiguration((hostingContext, config) =>
+ if (easyWay)
{
- config
- .SetBasePath(hostingContext.HostingEnvironment.ContentRootPath)
- .AddJsonFile("appsettings.json", true, true)
- .AddJsonFile($"appsettings.{hostingContext.HostingEnvironment.EnvironmentName}.json", true, true)
- .AddJsonFile("ocelot.json", false, false)
- .AddEnvironmentVariables();
- })
- .ConfigureServices(s =>
+ // Option #1. Define custom finder delegate to instantiate custom provider
+ // by default factory which is ServiceDiscoveryProviderFactory
+ s.AddSingleton((serviceProvider, config, downstreamRoute)
+ => new MyServiceDiscoveryProvider(serviceProvider, config, downstreamRoute));
+ }
+ else
{
- // Initialize from app configuration or hardcode/choose the best option.
- bool easyWay = true;
-
- if (easyWay)
- {
- // Option #1. Define custom finder delegate to instantiate custom provider
- // by default factory which is ServiceDiscoveryProviderFactory
- s.AddSingleton((serviceProvider, config, downstreamRoute)
- => new MyServiceDiscoveryProvider(serviceProvider, config, downstreamRoute));
- }
- else
- {
- // Option #2. Abstract from default factory (ServiceDiscoveryProviderFactory) and from FinderDelegate,
- // and build custom factory by implementation of the IServiceDiscoveryProviderFactory interface.
- s.RemoveAll();
- s.AddSingleton();
+ // Option #2. Abstract from default factory (ServiceDiscoveryProviderFactory) and from FinderDelegate,
+ // and build custom factory by implementation of the IServiceDiscoveryProviderFactory interface.
+ s.RemoveAll();
+ s.AddSingleton();
- // Will not be called, but it is required for internal validators, aka life hack
- s.AddSingleton((serviceProvider, config, downstreamRoute)
- => null);
- }
+ // Will not be called, but it is required for internal validators, aka life hack
+ s.AddSingleton((serviceProvider, config, downstreamRoute)
+ => null);
+ }
- s.AddOcelot();
- })
- .Configure(a =>
- {
- a.UseOcelot().Wait();
- })
- .Build();
+ s.AddOcelot();
+ })
+ .Configure(async a =>
+ {
+ await a.UseOcelot();
+ })
+ .Build()
+ .Run();
+ }
}
diff --git a/samples/ServiceDiscovery/DownstreamService/Ocelot.Samples.ServiceDiscovery.DownstreamService.csproj b/samples/ServiceDiscovery/DownstreamService/Ocelot.Samples.ServiceDiscovery.DownstreamService.csproj
index 163a956bb..60c62fd58 100644
--- a/samples/ServiceDiscovery/DownstreamService/Ocelot.Samples.ServiceDiscovery.DownstreamService.csproj
+++ b/samples/ServiceDiscovery/DownstreamService/Ocelot.Samples.ServiceDiscovery.DownstreamService.csproj
@@ -10,4 +10,8 @@
+
+
+
+
diff --git a/samples/ServiceDiscovery/DownstreamService/Program.cs b/samples/ServiceDiscovery/DownstreamService/Program.cs
index 2cfe402d1..b2778ce8d 100644
--- a/samples/ServiceDiscovery/DownstreamService/Program.cs
+++ b/samples/ServiceDiscovery/DownstreamService/Program.cs
@@ -1,5 +1,5 @@
global using Microsoft.AspNetCore.Mvc;
-using Microsoft.AspNetCore;
+using Ocelot.Samples.Web;
[assembly: ApiController]
@@ -9,9 +9,8 @@ public class Program
{
public static void Main(string[] args)
{
- WebHost.CreateDefaultBuilder(args)
+ DownstreamHostBuilder.Create(args)
.UseStartup()
- .Build()
- .Run();
+ .Build(); //.Run();
}
}
diff --git a/samples/ServiceFabric/ApiGateway/Ocelot.Samples.ServiceFabric.ApiGateway.csproj b/samples/ServiceFabric/ApiGateway/Ocelot.Samples.ServiceFabric.ApiGateway.csproj
index c9f886f75..72479cfc1 100644
--- a/samples/ServiceFabric/ApiGateway/Ocelot.Samples.ServiceFabric.ApiGateway.csproj
+++ b/samples/ServiceFabric/ApiGateway/Ocelot.Samples.ServiceFabric.ApiGateway.csproj
@@ -1,7 +1,7 @@
Stateless Web Service for Stateful OcelotApplicationApiGateway App
- net6.0;net7.0;net8.0
+ net8.0
disable
disable
OcelotApplicationApiGateway
@@ -19,5 +19,6 @@
+
diff --git a/samples/ServiceFabric/ApiGateway/WebCommunicationListener.cs b/samples/ServiceFabric/ApiGateway/WebCommunicationListener.cs
index 5bd5366b2..556beb0a1 100644
--- a/samples/ServiceFabric/ApiGateway/WebCommunicationListener.cs
+++ b/samples/ServiceFabric/ApiGateway/WebCommunicationListener.cs
@@ -9,115 +9,114 @@
using Microsoft.ServiceFabric.Services.Communication.Runtime;
using Ocelot.DependencyInjection;
using Ocelot.Middleware;
+using Ocelot.Samples.Web;
using System;
using System.Fabric;
using System.Globalization;
using System.Threading;
using System.Threading.Tasks;
-namespace OcelotApplicationApiGateway
+namespace OcelotApplicationApiGateway;
+
+public class WebCommunicationListener : ICommunicationListener
{
- public class WebCommunicationListener : ICommunicationListener
- {
- private readonly string _appRoot;
- private readonly ServiceContext _serviceInitializationParameters;
- private string _listeningAddress;
- private string _publishAddress;
+ private readonly string _appRoot;
+ private readonly ServiceContext _serviceInitializationParameters;
+ private string _listeningAddress;
+ private string _publishAddress;
- // OWIN server handle.
- private IWebHost _webHost;
+ // OWIN server handle.
+ private IWebHost _webHost;
- public WebCommunicationListener(string appRoot, ServiceContext serviceInitializationParameters)
- {
- _appRoot = appRoot;
- _serviceInitializationParameters = serviceInitializationParameters;
- }
+ public WebCommunicationListener(string appRoot, ServiceContext serviceInitializationParameters)
+ {
+ _appRoot = appRoot;
+ _serviceInitializationParameters = serviceInitializationParameters;
+ }
- public Task OpenAsync(CancellationToken cancellationToken)
- {
- ServiceEventSource.Current.Message("Initialize");
+ public Task OpenAsync(CancellationToken cancellationToken)
+ {
+ ServiceEventSource.Current.Message("Initialize");
- var serviceEndpoint = _serviceInitializationParameters.CodePackageActivationContext.GetEndpoint("WebEndpoint");
- var port = serviceEndpoint.Port;
+ var serviceEndpoint = _serviceInitializationParameters.CodePackageActivationContext.GetEndpoint("WebEndpoint");
+ var port = serviceEndpoint.Port;
- _listeningAddress = string.Format(
- CultureInfo.InvariantCulture,
- "http://+:{0}/{1}",
- port,
- string.IsNullOrWhiteSpace(_appRoot)
- ? string.Empty
- : _appRoot.TrimEnd('/') + '/');
+ _listeningAddress = string.Format(
+ CultureInfo.InvariantCulture,
+ "http://+:{0}/{1}",
+ port,
+ string.IsNullOrWhiteSpace(_appRoot)
+ ? string.Empty
+ : _appRoot.TrimEnd('/') + '/');
- _publishAddress = _listeningAddress.Replace("+", FabricRuntime.GetNodeContext().IPAddressOrFQDN);
+ _publishAddress = _listeningAddress.Replace("+", FabricRuntime.GetNodeContext().IPAddressOrFQDN);
- ServiceEventSource.Current.Message("Starting web server on {0}", _listeningAddress);
+ ServiceEventSource.Current.Message("Starting web server on {0}", _listeningAddress);
- try
+ try
+ {
+ _webHost = OcelotHostBuilder.Create()
+ .UseUrls(_listeningAddress)
+ .ConfigureAppConfiguration((hostingContext, config) =>
{
- _webHost = new WebHostBuilder()
- .UseKestrel()
- .UseUrls(_listeningAddress)
- .ConfigureAppConfiguration((hostingContext, config) =>
- {
- config
- .SetBasePath(hostingContext.HostingEnvironment.ContentRootPath)
- .AddJsonFile("appsettings.json", true, true)
- .AddJsonFile($"appsettings.{hostingContext.HostingEnvironment.EnvironmentName}.json", true, true)
- .AddJsonFile("ocelot.json", false, false)
- .AddEnvironmentVariables();
- })
- .ConfigureLogging((hostingContext, logging) =>
- {
- logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
- logging.AddConsole();
- })
- .ConfigureServices(s =>
- {
- s.AddOcelot();
- })
- .Configure(a =>
- {
- a.UseOcelot().Wait(cancellationToken);
- })
- .Build();
-
- _webHost.Start();
- }
- catch (Exception ex)
+ config
+ .SetBasePath(hostingContext.HostingEnvironment.ContentRootPath)
+ .AddJsonFile("appsettings.json", true, true)
+ .AddJsonFile($"appsettings.{hostingContext.HostingEnvironment.EnvironmentName}.json", true, true)
+ .AddJsonFile("ocelot.json", false, false)
+ .AddEnvironmentVariables();
+ })
+ .ConfigureLogging((hostingContext, logging) =>
{
- ServiceEventSource.Current.ServiceWebHostBuilderFailed(ex);
- }
+ logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
+ logging.AddConsole();
+ })
+ .ConfigureServices(s =>
+ {
+ s.AddOcelot();
+ })
+ .Configure(a =>
+ {
+ a.UseOcelot().Wait(cancellationToken);
+ })
+ .Build();
- return Task.FromResult(_publishAddress);
+ _webHost.Start();
}
-
- public Task CloseAsync(CancellationToken cancellationToken)
+ catch (Exception ex)
{
- StopAll();
- return Task.FromResult(true);
+ ServiceEventSource.Current.ServiceWebHostBuilderFailed(ex);
}
- public void Abort()
- {
- StopAll();
- }
+ return Task.FromResult(_publishAddress);
+ }
+
+ public Task CloseAsync(CancellationToken cancellationToken)
+ {
+ StopAll();
+ return Task.FromResult(true);
+ }
+
+ public void Abort()
+ {
+ StopAll();
+ }
- ///
- /// Stops, cancels, and disposes everything.
- ///
- private void StopAll()
+ ///
+ /// Stops, cancels, and disposes everything.
+ ///
+ private void StopAll()
+ {
+ try
{
- try
- {
- if (_webHost != null)
- {
- ServiceEventSource.Current.Message("Stopping web server.");
- _webHost.Dispose();
- }
- }
- catch (ObjectDisposedException)
+ if (_webHost != null)
{
+ ServiceEventSource.Current.Message("Stopping web server.");
+ _webHost.Dispose();
}
}
+ catch (ObjectDisposedException)
+ {
+ }
}
}
diff --git a/samples/ServiceFabric/DownstreamService/ApiGateway.cs b/samples/ServiceFabric/DownstreamService/ApiGateway.cs
index 186c74662..5ce89fbc5 100644
--- a/samples/ServiceFabric/DownstreamService/ApiGateway.cs
+++ b/samples/ServiceFabric/DownstreamService/ApiGateway.cs
@@ -4,53 +4,49 @@
using Microsoft.ServiceFabric.Services.Communication.AspNetCore;
using Microsoft.ServiceFabric.Services.Communication.Runtime;
using Microsoft.ServiceFabric.Services.Runtime;
+using Ocelot.Samples.Web;
using System;
using System.Collections.Generic;
using System.Fabric;
using System.IO;
-namespace OcelotApplicationService
+namespace OcelotApplicationService;
+
+///
+/// The FabricRuntime creates an instance of this class for each service type instance.
+///
+internal sealed class ApiGateway : StatelessService
{
+ public ApiGateway(StatelessServiceContext context)
+ : base(context) { }
+
///
- /// The FabricRuntime creates an instance of this class for each service type instance.
+ /// Optional override to create listeners (like tcp, http) for this service instance.
///
- internal sealed class ApiGateway : StatelessService
+ /// The collection of listeners.
+ protected override IEnumerable CreateServiceInstanceListeners()
{
- public ApiGateway(StatelessServiceContext context)
- : base(context)
- { }
-
- ///
- /// Optional override to create listeners (like tcp, http) for this service instance.
- ///
- /// The collection of listeners.
- protected override IEnumerable CreateServiceInstanceListeners()
+ return new ServiceInstanceListener[]
{
- return new ServiceInstanceListener[]
- {
- new(serviceContext =>
- new KestrelCommunicationListener(serviceContext, "ServiceEndpoint", (url, listener) =>
- {
- Console.WriteLine($"Starting Kestrel on {url}");
- ServiceEventSource.Current.ServiceMessage(serviceContext, $"Starting Kestrel on {url}");
-
- return new WebHostBuilder()
- .UseKestrel()
- .ConfigureServices(
- services => services
- .AddSingleton(serviceContext))
- .UseContentRoot(Directory.GetCurrentDirectory())
- .UseServiceFabricIntegration(listener, ServiceFabricIntegrationOptions.UseUniqueServiceUrl)
- .UseStartup()
- .UseUrls(url)
- .ConfigureLogging((hostingContext, logging) =>
- {
- logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
- logging.AddConsole();
- })
- .Build();
- }))
- };
- }
+ new(serviceContext =>
+ new KestrelCommunicationListener(serviceContext, "ServiceEndpoint", (url, listener) =>
+ {
+ Console.WriteLine($"Starting Kestrel on {url}");
+ ServiceEventSource.Current.ServiceMessage(serviceContext, $"Starting Kestrel on {url}");
+ return OcelotHostBuilder.Create()
+ .UseKestrel()
+ .ConfigureServices(services => services.AddSingleton(serviceContext))
+ .UseContentRoot(Directory.GetCurrentDirectory())
+ .UseServiceFabricIntegration(listener, ServiceFabricIntegrationOptions.UseUniqueServiceUrl)
+ .UseStartup()
+ .UseUrls(url)
+ .ConfigureLogging((hostingContext, logging) =>
+ {
+ logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
+ logging.AddConsole();
+ })
+ .Build();
+ }))
+ };
}
}
diff --git a/samples/ServiceFabric/DownstreamService/Ocelot.Samples.ServiceFabric.DownstreamService.csproj b/samples/ServiceFabric/DownstreamService/Ocelot.Samples.ServiceFabric.DownstreamService.csproj
index 6dc51c893..43aa8c895 100644
--- a/samples/ServiceFabric/DownstreamService/Ocelot.Samples.ServiceFabric.DownstreamService.csproj
+++ b/samples/ServiceFabric/DownstreamService/Ocelot.Samples.ServiceFabric.DownstreamService.csproj
@@ -1,7 +1,7 @@
Stateless Service Application
- net6.0;net7.0;net8.0
+ net8.0
disable
disable
OcelotApplicationService
@@ -17,4 +17,7 @@
+
+
+
diff --git a/samples/ServiceFabric/DownstreamService/Program.cs b/samples/ServiceFabric/DownstreamService/Program.cs
index e1d85d2fa..e10c3763d 100644
--- a/samples/ServiceFabric/DownstreamService/Program.cs
+++ b/samples/ServiceFabric/DownstreamService/Program.cs
@@ -2,35 +2,34 @@
using System;
using System.Threading;
-namespace OcelotApplicationService
+namespace OcelotApplicationService;
+
+internal static class Program
{
- internal static class Program
+ ///
+ /// This is the entry point of the service host process.
+ ///
+ private static void Main()
{
- ///
- /// This is the entry point of the service host process.
- ///
- private static void Main()
+ try
{
- try
- {
- // The ServiceManifest.XML file defines one or more service type names.
- // Registering a service maps a service type name to a .NET type.
- // When Service Fabric creates an instance of this service type,
- // an instance of the class is created in this host process.
+ // The ServiceManifest.XML file defines one or more service type names.
+ // Registering a service maps a service type name to a .NET type.
+ // When Service Fabric creates an instance of this service type,
+ // an instance of the class is created in this host process.
- ServiceRuntime.RegisterServiceAsync("OcelotApplicationServiceType",
- context => new ApiGateway(context)).GetAwaiter().GetResult();
+ ServiceRuntime.RegisterServiceAsync("OcelotApplicationServiceType",
+ context => new ApiGateway(context)).GetAwaiter().GetResult();
- ServiceEventSource.Current.ServiceTypeRegistered(Environment.ProcessId, nameof(ApiGateway));
+ ServiceEventSource.Current.ServiceTypeRegistered(Environment.ProcessId, nameof(ApiGateway));
- // Prevents this host process from terminating so services keeps running.
- Thread.Sleep(Timeout.Infinite);
- }
- catch (Exception e)
- {
- ServiceEventSource.Current.ServiceHostInitializationFailed(e.ToString());
- throw;
- }
+ // Prevents this host process from terminating so services keeps running.
+ Thread.Sleep(Timeout.Infinite);
+ }
+ catch (Exception e)
+ {
+ ServiceEventSource.Current.ServiceHostInitializationFailed(e.ToString());
+ throw;
}
}
}
diff --git a/samples/ServiceFabric/DownstreamService/ServiceEventSource.cs b/samples/ServiceFabric/DownstreamService/ServiceEventSource.cs
index f58ddcbcc..1499cc116 100644
--- a/samples/ServiceFabric/DownstreamService/ServiceEventSource.cs
+++ b/samples/ServiceFabric/DownstreamService/ServiceEventSource.cs
@@ -3,182 +3,181 @@
using System.Fabric;
using System.Threading.Tasks;
-namespace OcelotApplicationService
+namespace OcelotApplicationService;
+
+[EventSource(Name = "MyCompany-ServiceOcelotApplication-OcelotService")]
+internal sealed class ServiceEventSource : EventSource
{
- [EventSource(Name = "MyCompany-ServiceOcelotApplication-OcelotService")]
- internal sealed class ServiceEventSource : EventSource
- {
- public static readonly ServiceEventSource Current = new();
+ public static readonly ServiceEventSource Current = new();
- static ServiceEventSource()
- {
- // A workaround for the problem where ETW activities do not get tracked until Tasks infrastructure is initialized.
- // This problem will be fixed in .NET Framework 4.6.2.
- Task.Run(() => { });
- }
+ static ServiceEventSource()
+ {
+ // A workaround for the problem where ETW activities do not get tracked until Tasks infrastructure is initialized.
+ // This problem will be fixed in .NET Framework 4.6.2.
+ Task.Run(() => { });
+ }
- // Instance constructor is private to enforce singleton semantics
- private ServiceEventSource() : base() { }
+ // Instance constructor is private to enforce singleton semantics
+ private ServiceEventSource() : base() { }
- #region Keywords
- // Event keywords can be used to categorize events.
- // Each keyword is a bit flag. A single event can be associated with multiple keywords (via EventAttribute.Keywords property).
- // Keywords must be defined as a public class named 'Keywords' inside EventSource that uses them.
- public static class Keywords
- {
- public const EventKeywords Requests = (EventKeywords)0x1L;
- public const EventKeywords ServiceInitialization = (EventKeywords)0x2L;
- }
- #endregion
-
- #region Events
- // Define an instance method for each event you want to record and apply an [Event] attribute to it.
- // The method name is the name of the event.
- // Pass any parameters you want to record with the event (only primitive integer types, DateTime, Guid & string are allowed).
- // Each event method implementation should check whether the event source is enabled, and if it is, call WriteEvent() method to raise the event.
- // The number and types of arguments passed to every event method must exactly match what is passed to WriteEvent().
- // Put [NonEvent] attribute on all methods that do not define an event.
- // For more information see https://msdn.microsoft.com/en-us/library/system.diagnostics.tracing.eventsource.aspx
-
- [NonEvent]
- public void Message(string message, params object[] args)
+ #region Keywords
+ // Event keywords can be used to categorize events.
+ // Each keyword is a bit flag. A single event can be associated with multiple keywords (via EventAttribute.Keywords property).
+ // Keywords must be defined as a public class named 'Keywords' inside EventSource that uses them.
+ public static class Keywords
+ {
+ public const EventKeywords Requests = (EventKeywords)0x1L;
+ public const EventKeywords ServiceInitialization = (EventKeywords)0x2L;
+ }
+ #endregion
+
+ #region Events
+ // Define an instance method for each event you want to record and apply an [Event] attribute to it.
+ // The method name is the name of the event.
+ // Pass any parameters you want to record with the event (only primitive integer types, DateTime, Guid & string are allowed).
+ // Each event method implementation should check whether the event source is enabled, and if it is, call WriteEvent() method to raise the event.
+ // The number and types of arguments passed to every event method must exactly match what is passed to WriteEvent().
+ // Put [NonEvent] attribute on all methods that do not define an event.
+ // For more information see https://msdn.microsoft.com/en-us/library/system.diagnostics.tracing.eventsource.aspx
+
+ [NonEvent]
+ public void Message(string message, params object[] args)
+ {
+ if (IsEnabled())
{
- if (IsEnabled())
- {
- var finalMessage = string.Format(message, args);
- Message(finalMessage);
- }
+ var finalMessage = string.Format(message, args);
+ Message(finalMessage);
}
+ }
- private const int MessageEventId = 1;
- [Event(MessageEventId, Level = EventLevel.Informational, Message = "{0}")]
- public void Message(string message)
+ private const int MessageEventId = 1;
+ [Event(MessageEventId, Level = EventLevel.Informational, Message = "{0}")]
+ public void Message(string message)
+ {
+ if (IsEnabled())
{
- if (IsEnabled())
- {
- WriteEvent(MessageEventId, message);
- }
+ WriteEvent(MessageEventId, message);
}
+ }
- [NonEvent]
- public void ServiceMessage(ServiceContext serviceContext, string message, params object[] args)
+ [NonEvent]
+ public void ServiceMessage(ServiceContext serviceContext, string message, params object[] args)
+ {
+ if (IsEnabled())
{
- if (IsEnabled())
- {
-
- var finalMessage = string.Format(message, args);
- ServiceMessage(
- serviceContext.ServiceName.ToString(),
- serviceContext.ServiceTypeName,
- GetReplicaOrInstanceId(serviceContext),
- serviceContext.PartitionId,
- serviceContext.CodePackageActivationContext.ApplicationName,
- serviceContext.CodePackageActivationContext.ApplicationTypeName,
- serviceContext.NodeContext.NodeName,
- finalMessage);
- }
+
+ var finalMessage = string.Format(message, args);
+ ServiceMessage(
+ serviceContext.ServiceName.ToString(),
+ serviceContext.ServiceTypeName,
+ GetReplicaOrInstanceId(serviceContext),
+ serviceContext.PartitionId,
+ serviceContext.CodePackageActivationContext.ApplicationName,
+ serviceContext.CodePackageActivationContext.ApplicationTypeName,
+ serviceContext.NodeContext.NodeName,
+ finalMessage);
}
+ }
- // For very high-frequency events it might be advantageous to raise events using WriteEventCore API.
- // This results in more efficient parameter handling, but requires explicit allocation of EventData structure and unsafe code.
- // To enable this code path, define UNSAFE conditional compilation symbol and turn on unsafe code support in project properties.
- private const int ServiceMessageEventId = 2;
- [Event(ServiceMessageEventId, Level = EventLevel.Informational, Message = "{7}")]
- private
+ // For very high-frequency events it might be advantageous to raise events using WriteEventCore API.
+ // This results in more efficient parameter handling, but requires explicit allocation of EventData structure and unsafe code.
+ // To enable this code path, define UNSAFE conditional compilation symbol and turn on unsafe code support in project properties.
+ private const int ServiceMessageEventId = 2;
+ [Event(ServiceMessageEventId, Level = EventLevel.Informational, Message = "{7}")]
+ private
#if UNSAFE
- unsafe
+ unsafe
#endif
- void ServiceMessage(
- string serviceName,
- string serviceTypeName,
- long replicaOrInstanceId,
- Guid partitionId,
- string applicationName,
- string applicationTypeName,
- string nodeName,
- string message)
- {
+ void ServiceMessage(
+ string serviceName,
+ string serviceTypeName,
+ long replicaOrInstanceId,
+ Guid partitionId,
+ string applicationName,
+ string applicationTypeName,
+ string nodeName,
+ string message)
+ {
#if !UNSAFE
- WriteEvent(ServiceMessageEventId, serviceName, serviceTypeName, replicaOrInstanceId, partitionId, applicationName, applicationTypeName, nodeName, message);
+ WriteEvent(ServiceMessageEventId, serviceName, serviceTypeName, replicaOrInstanceId, partitionId, applicationName, applicationTypeName, nodeName, message);
#else
- const int numArgs = 8;
- fixed (char* pServiceName = serviceName, pServiceTypeName = serviceTypeName, pApplicationName = applicationName, pApplicationTypeName = applicationTypeName, pNodeName = nodeName, pMessage = message)
- {
- EventData* eventData = stackalloc EventData[numArgs];
- eventData[0] = new EventData { DataPointer = (IntPtr) pServiceName, Size = SizeInBytes(serviceName) };
- eventData[1] = new EventData { DataPointer = (IntPtr) pServiceTypeName, Size = SizeInBytes(serviceTypeName) };
- eventData[2] = new EventData { DataPointer = (IntPtr) (&replicaOrInstanceId), Size = sizeof(long) };
- eventData[3] = new EventData { DataPointer = (IntPtr) (&partitionId), Size = sizeof(Guid) };
- eventData[4] = new EventData { DataPointer = (IntPtr) pApplicationName, Size = SizeInBytes(applicationName) };
- eventData[5] = new EventData { DataPointer = (IntPtr) pApplicationTypeName, Size = SizeInBytes(applicationTypeName) };
- eventData[6] = new EventData { DataPointer = (IntPtr) pNodeName, Size = SizeInBytes(nodeName) };
- eventData[7] = new EventData { DataPointer = (IntPtr) pMessage, Size = SizeInBytes(message) };
-
- WriteEventCore(ServiceMessageEventId, numArgs, eventData);
- }
-#endif
- }
-
- private const int ServiceTypeRegisteredEventId = 3;
- [Event(ServiceTypeRegisteredEventId, Level = EventLevel.Informational, Message = "Service host process {0} registered service type {1}", Keywords = Keywords.ServiceInitialization)]
- public void ServiceTypeRegistered(int hostProcessId, string serviceType)
+ const int numArgs = 8;
+ fixed (char* pServiceName = serviceName, pServiceTypeName = serviceTypeName, pApplicationName = applicationName, pApplicationTypeName = applicationTypeName, pNodeName = nodeName, pMessage = message)
{
- WriteEvent(ServiceTypeRegisteredEventId, hostProcessId, serviceType);
+ EventData* eventData = stackalloc EventData[numArgs];
+ eventData[0] = new EventData { DataPointer = (IntPtr) pServiceName, Size = SizeInBytes(serviceName) };
+ eventData[1] = new EventData { DataPointer = (IntPtr) pServiceTypeName, Size = SizeInBytes(serviceTypeName) };
+ eventData[2] = new EventData { DataPointer = (IntPtr) (&replicaOrInstanceId), Size = sizeof(long) };
+ eventData[3] = new EventData { DataPointer = (IntPtr) (&partitionId), Size = sizeof(Guid) };
+ eventData[4] = new EventData { DataPointer = (IntPtr) pApplicationName, Size = SizeInBytes(applicationName) };
+ eventData[5] = new EventData { DataPointer = (IntPtr) pApplicationTypeName, Size = SizeInBytes(applicationTypeName) };
+ eventData[6] = new EventData { DataPointer = (IntPtr) pNodeName, Size = SizeInBytes(nodeName) };
+ eventData[7] = new EventData { DataPointer = (IntPtr) pMessage, Size = SizeInBytes(message) };
+
+ WriteEventCore(ServiceMessageEventId, numArgs, eventData);
}
+#endif
+ }
- private const int ServiceHostInitializationFailedEventId = 4;
- [Event(ServiceHostInitializationFailedEventId, Level = EventLevel.Error, Message = "Service host initialization failed", Keywords = Keywords.ServiceInitialization)]
- public void ServiceHostInitializationFailed(string exception)
- {
- WriteEvent(ServiceHostInitializationFailedEventId, exception);
- }
+ private const int ServiceTypeRegisteredEventId = 3;
+ [Event(ServiceTypeRegisteredEventId, Level = EventLevel.Informational, Message = "Service host process {0} registered service type {1}", Keywords = Keywords.ServiceInitialization)]
+ public void ServiceTypeRegistered(int hostProcessId, string serviceType)
+ {
+ WriteEvent(ServiceTypeRegisteredEventId, hostProcessId, serviceType);
+ }
+
+ private const int ServiceHostInitializationFailedEventId = 4;
+ [Event(ServiceHostInitializationFailedEventId, Level = EventLevel.Error, Message = "Service host initialization failed", Keywords = Keywords.ServiceInitialization)]
+ public void ServiceHostInitializationFailed(string exception)
+ {
+ WriteEvent(ServiceHostInitializationFailedEventId, exception);
+ }
+
+ // A pair of events sharing the same name prefix with a "Start"/"Stop" suffix implicitly marks boundaries of an event tracing activity.
+ // These activities can be automatically picked up by debugging and profiling tools, which can compute their execution time, child activities,
+ // and other statistics.
+ private const int ServiceRequestStartEventId = 5;
+ [Event(ServiceRequestStartEventId, Level = EventLevel.Informational, Message = "Service request '{0}' started", Keywords = Keywords.Requests)]
+ public void ServiceRequestStart(string requestTypeName)
+ {
+ WriteEvent(ServiceRequestStartEventId, requestTypeName);
+ }
- // A pair of events sharing the same name prefix with a "Start"/"Stop" suffix implicitly marks boundaries of an event tracing activity.
- // These activities can be automatically picked up by debugging and profiling tools, which can compute their execution time, child activities,
- // and other statistics.
- private const int ServiceRequestStartEventId = 5;
- [Event(ServiceRequestStartEventId, Level = EventLevel.Informational, Message = "Service request '{0}' started", Keywords = Keywords.Requests)]
- public void ServiceRequestStart(string requestTypeName)
+ private const int ServiceRequestStopEventId = 6;
+ [Event(ServiceRequestStopEventId, Level = EventLevel.Informational, Message = "Service request '{0}' finished", Keywords = Keywords.Requests)]
+ public void ServiceRequestStop(string requestTypeName, string exception = "")
+ {
+ WriteEvent(ServiceRequestStopEventId, requestTypeName, exception);
+ }
+ #endregion
+
+ #region Private methods
+ private static long GetReplicaOrInstanceId(ServiceContext context)
+ {
+ if (context is StatelessServiceContext stateless)
{
- WriteEvent(ServiceRequestStartEventId, requestTypeName);
+ return stateless.InstanceId;
}
- private const int ServiceRequestStopEventId = 6;
- [Event(ServiceRequestStopEventId, Level = EventLevel.Informational, Message = "Service request '{0}' finished", Keywords = Keywords.Requests)]
- public void ServiceRequestStop(string requestTypeName, string exception = "")
+ if (context is StatefulServiceContext stateful)
{
- WriteEvent(ServiceRequestStopEventId, requestTypeName, exception);
+ return stateful.ReplicaId;
}
- #endregion
- #region Private methods
- private static long GetReplicaOrInstanceId(ServiceContext context)
+ throw new NotSupportedException("Context type not supported.");
+ }
+#if UNSAFE
+ private int SizeInBytes(string s)
+ {
+ if (s == null)
{
- if (context is StatelessServiceContext stateless)
- {
- return stateless.InstanceId;
- }
-
- if (context is StatefulServiceContext stateful)
- {
- return stateful.ReplicaId;
- }
-
- throw new NotSupportedException("Context type not supported.");
+ return 0;
}
-#if UNSAFE
- private int SizeInBytes(string s)
+ else
{
- if (s == null)
- {
- return 0;
- }
- else
- {
- return (s.Length + 1) * sizeof(char);
- }
+ return (s.Length + 1) * sizeof(char);
}
-#endif
- #endregion
}
+#endif
+ #endregion
}
diff --git a/samples/ServiceFabric/DownstreamService/Startup.cs b/samples/ServiceFabric/DownstreamService/Startup.cs
index 53b408e90..73acff151 100644
--- a/samples/ServiceFabric/DownstreamService/Startup.cs
+++ b/samples/ServiceFabric/DownstreamService/Startup.cs
@@ -4,30 +4,29 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
-namespace OcelotApplicationService
+namespace OcelotApplicationService;
+
+public class Startup
{
- public class Startup
+ public Startup(IConfiguration configuration)
{
- public Startup(IConfiguration configuration)
- {
- Configuration = configuration;
- }
+ Configuration = configuration;
+ }
- public IConfiguration Configuration { get; }
+ public IConfiguration Configuration { get; }
- // This method gets called by the runtime. Use this method to add services to the container.
- public void ConfigureServices(IServiceCollection services)
- {
- services.AddMvc();
- }
+ // This method gets called by the runtime. Use this method to add services to the container.
+ public void ConfigureServices(IServiceCollection services)
+ {
+ services.AddMvc();
+ }
- // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
- public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
+ // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
+ public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
+ {
+ if (env.IsDevelopment())
{
- if (env.IsDevelopment())
- {
- app.UseDeveloperExceptionPage();
- }
+ app.UseDeveloperExceptionPage();
}
}
}
diff --git a/samples/Web/DownstreamHostBuilder.cs b/samples/Web/DownstreamHostBuilder.cs
new file mode 100644
index 000000000..d3b6ebac4
--- /dev/null
+++ b/samples/Web/DownstreamHostBuilder.cs
@@ -0,0 +1,27 @@
+using Microsoft.AspNetCore;
+
+namespace Ocelot.Samples.Web;
+
+public sealed class DownstreamHostBuilder : WebHostBuilder
+{
+ public static IWebHostBuilder Create() => WebHost
+ .CreateDefaultBuilder()
+ .UseDefaultServiceProvider(WithEnabledValidateScopes);
+ public static IWebHostBuilder Create(Action configure) => WebHost
+ .CreateDefaultBuilder()
+ .UseDefaultServiceProvider(configure + WithEnabledValidateScopes);
+
+ public static IWebHostBuilder Create(string[] args) => WebHost
+ .CreateDefaultBuilder(args)
+ .UseDefaultServiceProvider(WithEnabledValidateScopes);
+
+ public static IWebHostBuilder Create(string[] args, Action configure) => WebHost
+ .CreateDefaultBuilder(args)
+ .UseDefaultServiceProvider(configure + WithEnabledValidateScopes);
+
+ public static void WithEnabledValidateScopes(ServiceProviderOptions options)
+ => options.ValidateScopes = true;
+
+ // TODO Add more standard Ocelot setup
+ public static IWebHostBuilder BasicSetup() => Create(); // in CreateDefaultBuilder() implicitly calls -> .UseKestrel().UseContentRoot(Directory.GetCurrentDirectory());
+}
diff --git a/samples/Web/Ocelot.Samples.Web.csproj b/samples/Web/Ocelot.Samples.Web.csproj
new file mode 100644
index 000000000..0433d962d
--- /dev/null
+++ b/samples/Web/Ocelot.Samples.Web.csproj
@@ -0,0 +1,10 @@
+
+
+
+ 0.0.0-dev
+ net8.0
+ enable
+ enable
+
+
+
diff --git a/samples/Web/OcelotHostBuilder.cs b/samples/Web/OcelotHostBuilder.cs
new file mode 100644
index 000000000..4d21ca600
--- /dev/null
+++ b/samples/Web/OcelotHostBuilder.cs
@@ -0,0 +1,27 @@
+using Microsoft.AspNetCore;
+
+namespace Ocelot.Samples.Web;
+
+public sealed class OcelotHostBuilder : WebHostBuilder
+{
+ public static IWebHostBuilder Create() => WebHost
+ .CreateDefaultBuilder()
+ .UseDefaultServiceProvider(WithEnabledValidateScopes);
+ public static IWebHostBuilder Create(Action configure) => WebHost
+ .CreateDefaultBuilder()
+ .UseDefaultServiceProvider(configure + WithEnabledValidateScopes);
+
+ public static IWebHostBuilder Create(string[] args) => WebHost
+ .CreateDefaultBuilder(args)
+ .UseDefaultServiceProvider(WithEnabledValidateScopes);
+
+ public static IWebHostBuilder Create(string[] args, Action configure) => WebHost
+ .CreateDefaultBuilder(args)
+ .UseDefaultServiceProvider(configure + WithEnabledValidateScopes);
+
+ public static void WithEnabledValidateScopes(ServiceProviderOptions options)
+ => options.ValidateScopes = true;
+
+ // TODO Add more standard Ocelot setup
+ public static IWebHostBuilder BasicSetup() => Create(); // in CreateDefaultBuilder() implicitly calls -> .UseKestrel().UseContentRoot(Directory.GetCurrentDirectory());
+}
diff --git a/samples/Web/Program.cs b/samples/Web/Program.cs
new file mode 100644
index 000000000..40d9a78b7
--- /dev/null
+++ b/samples/Web/Program.cs
@@ -0,0 +1,6 @@
+namespace Ocelot.Samples.Web;
+
+public class Program
+{
+ public static void Main(string[] args) { }
+}
diff --git a/samples/Web/Properties/launchSettings.json b/samples/Web/Properties/launchSettings.json
new file mode 100644
index 000000000..4aac128b6
--- /dev/null
+++ b/samples/Web/Properties/launchSettings.json
@@ -0,0 +1,12 @@
+{
+ "profiles": {
+ "Ocelot.Samples.Helpers": {
+ "commandName": "Project",
+ "launchBrowser": true,
+ "environmentVariables": {
+ "ASPNETCORE_ENVIRONMENT": "Development"
+ },
+ "applicationUrl": "https://localhost:63629;http://localhost:63630"
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/Ocelot.Provider.Eureka/EurekaMiddlewareConfigurationProvider.cs b/src/Ocelot.Provider.Eureka/EurekaMiddlewareConfigurationProvider.cs
index 5f6c800ab..0c2d6ecc8 100644
--- a/src/Ocelot.Provider.Eureka/EurekaMiddlewareConfigurationProvider.cs
+++ b/src/Ocelot.Provider.Eureka/EurekaMiddlewareConfigurationProvider.cs
@@ -3,27 +3,26 @@
using Ocelot.Configuration.Repository;
using Ocelot.Middleware;
-namespace Ocelot.Provider.Eureka
+namespace Ocelot.Provider.Eureka;
+
+public class EurekaMiddlewareConfigurationProvider
{
- public class EurekaMiddlewareConfigurationProvider
+ public static OcelotMiddlewareConfigurationDelegate Get { get; } = builder =>
{
- public static OcelotMiddlewareConfigurationDelegate Get { get; } = builder =>
- {
- var internalConfigRepo = builder.ApplicationServices.GetService();
-
- var config = internalConfigRepo.Get();
-
- if (UsingEurekaServiceDiscoveryProvider(config.Data))
- {
- //builder.UseDiscoveryClient();
- }
+ var internalConfigRepo = builder.ApplicationServices.GetService();
- return Task.CompletedTask;
- };
+ var config = internalConfigRepo.Get();
- private static bool UsingEurekaServiceDiscoveryProvider(IInternalConfiguration configuration)
+ if (UsingEurekaServiceDiscoveryProvider(config.Data))
{
- return configuration?.ServiceProviderConfiguration != null && configuration.ServiceProviderConfiguration.Type?.ToLower() == "eureka";
+ //builder.UseDiscoveryClient();
}
+
+ return Task.CompletedTask;
+ };
+
+ private static bool UsingEurekaServiceDiscoveryProvider(IInternalConfiguration configuration)
+ {
+ return configuration?.ServiceProviderConfiguration != null && configuration.ServiceProviderConfiguration.Type?.ToLower() == "eureka";
}
}
diff --git a/src/Ocelot.Provider.Eureka/OcelotBuilderExtensions.cs b/src/Ocelot.Provider.Eureka/OcelotBuilderExtensions.cs
index ae4348b1f..40062b1f4 100644
--- a/src/Ocelot.Provider.Eureka/OcelotBuilderExtensions.cs
+++ b/src/Ocelot.Provider.Eureka/OcelotBuilderExtensions.cs
@@ -2,17 +2,16 @@
using Ocelot.DependencyInjection;
using Steeltoe.Discovery.Client;
-namespace Ocelot.Provider.Eureka
+namespace Ocelot.Provider.Eureka;
+
+public static class OcelotBuilderExtensions
{
- public static class OcelotBuilderExtensions
+ public static IOcelotBuilder AddEureka(this IOcelotBuilder builder)
{
- public static IOcelotBuilder AddEureka(this IOcelotBuilder builder)
- {
- builder.Services
- .AddDiscoveryClient(builder.Configuration)
- .AddSingleton(EurekaProviderFactory.Get)
- .AddSingleton(EurekaMiddlewareConfigurationProvider.Get);
- return builder;
- }
+ builder.Services
+ .AddDiscoveryClient(builder.Configuration)
+ .AddSingleton(EurekaProviderFactory.Get)
+ .AddSingleton(EurekaMiddlewareConfigurationProvider.Get);
+ return builder;
}
}
diff --git a/src/Ocelot/DependencyInjection/OcelotBuilder.cs b/src/Ocelot/DependencyInjection/OcelotBuilder.cs
index 1e21081ad..642697744 100644
--- a/src/Ocelot/DependencyInjection/OcelotBuilder.cs
+++ b/src/Ocelot/DependencyInjection/OcelotBuilder.cs
@@ -1,4 +1,3 @@
-using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
diff --git a/src/Ocelot/DependencyInjection/ServiceCollectionExtensions.cs b/src/Ocelot/DependencyInjection/ServiceCollectionExtensions.cs
index 864419f77..97401639b 100644
--- a/src/Ocelot/DependencyInjection/ServiceCollectionExtensions.cs
+++ b/src/Ocelot/DependencyInjection/ServiceCollectionExtensions.cs
@@ -77,13 +77,13 @@ private static IConfiguration DefaultConfiguration(IWebHostEnvironment env)
private static IConfiguration FindConfiguration(this IServiceCollection services, IWebHostEnvironment env)
{
- var descriptor = services.FirstOrDefault(descriptor => descriptor.ServiceType == typeof(IConfiguration));
+ var descriptor = services.FirstOrDefault(x => x.ServiceType == typeof(IConfiguration));
if (descriptor == null)
{
return DefaultConfiguration(env);
}
- var provider = new ServiceCollection().Add(descriptor).BuildServiceProvider();
+ var provider = new ServiceCollection().Add(descriptor).BuildServiceProvider(true);
var configuration = provider.GetService();
return configuration ?? DefaultConfiguration(env);
}
diff --git a/test/Ocelot.AcceptanceTests/AggregateTests.cs b/test/Ocelot.AcceptanceTests/AggregateTests.cs
index cf38c6648..558a7131c 100644
--- a/test/Ocelot.AcceptanceTests/AggregateTests.cs
+++ b/test/Ocelot.AcceptanceTests/AggregateTests.cs
@@ -578,7 +578,7 @@ public void Should_return_response_200_with_user_forwarding()
.And(x => x.GivenServiceIsRunning(1, port2, "/", 200, "{Hello from Tom}"))
.And(x => auth.GivenIHaveAToken(identityServerUrl))
.And(x => auth.GivenThereIsAConfiguration(configuration))
- .And(x => auth.GivenOcelotIsRunningWithServices(configureServices, configureApp, true))
+ .And(x => auth.GivenOcelotIsRunningWithServices(configureServices, configureApp))
.And(x => auth.GivenIHaveAddedATokenToMyRequest())
.When(x => auth.WhenIGetUrlOnTheApiGateway("/"))
.Then(x => auth.ThenTheStatusCodeShouldBe(HttpStatusCode.OK))
@@ -727,9 +727,7 @@ private void GivenOcelotIsRunningWithSpecificAggregatorsRegisteredInDi
{
config.SetBasePath(hostingContext.HostingEnvironment.ContentRootPath);
diff --git a/test/Ocelot.AcceptanceTests/Authentication/AuthenticationSteps.cs b/test/Ocelot.AcceptanceTests/Authentication/AuthenticationSteps.cs
index b9e626f00..81abf816d 100644
--- a/test/Ocelot.AcceptanceTests/Authentication/AuthenticationSteps.cs
+++ b/test/Ocelot.AcceptanceTests/Authentication/AuthenticationSteps.cs
@@ -78,7 +78,7 @@ public static IWebHostBuilder CreateIdentityServer(string url, AccessTokenType t
{
apiScopes ??= new string[] { "api" };
clients ??= new Client[] { DefaultClient(tokenType, apiScopes) };
- var builder = new WebHostBuilder()
+ var builder = TestHostBuilder.Create()
.UseUrls(url)
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
diff --git a/test/Ocelot.AcceptanceTests/AuthorizationTests.cs b/test/Ocelot.AcceptanceTests/AuthorizationTests.cs
index 77db4efcc..b9e43efdc 100644
--- a/test/Ocelot.AcceptanceTests/AuthorizationTests.cs
+++ b/test/Ocelot.AcceptanceTests/AuthorizationTests.cs
@@ -310,7 +310,7 @@ private void GivenThereIsAServiceRunningOn(string url, int statusCode, string re
private async Task GivenThereIsAnIdentityServerOn(string url, string apiName, AccessTokenType tokenType)
{
- _identityServerBuilder = new WebHostBuilder()
+ _identityServerBuilder = TestHostBuilder.Create()
.UseUrls(url)
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
@@ -397,7 +397,7 @@ private async Task GivenThereIsAnIdentityServerOn(string url, string apiName, Ac
private async Task GivenThereIsAnIdentityServerOn(string url, string apiName, AccessTokenType tokenType, List users)
{
- _identityServerBuilder = new WebHostBuilder()
+ _identityServerBuilder = TestHostBuilder.Create()
.UseUrls(url)
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
diff --git a/test/Ocelot.AcceptanceTests/ButterflyTracingTests.cs b/test/Ocelot.AcceptanceTests/ButterflyTracingTests.cs
index a90560f02..da762a63d 100644
--- a/test/Ocelot.AcceptanceTests/ButterflyTracingTests.cs
+++ b/test/Ocelot.AcceptanceTests/ButterflyTracingTests.cs
@@ -149,7 +149,7 @@ public void should_return_tracing_header()
private void GivenServiceOneIsRunning(string baseUrl, string basePath, int statusCode, string responseBody, string butterflyUrl)
{
- _serviceOneBuilder = new WebHostBuilder()
+ _serviceOneBuilder = TestHostBuilder.Create()
.UseUrls(baseUrl)
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
@@ -189,7 +189,7 @@ private void GivenServiceOneIsRunning(string baseUrl, string basePath, int statu
private void GivenFakeButterfly(string baseUrl)
{
- _fakeButterfly = new WebHostBuilder()
+ _fakeButterfly = TestHostBuilder.Create()
.UseUrls(baseUrl)
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
@@ -209,7 +209,7 @@ private void GivenFakeButterfly(string baseUrl)
private void GivenServiceTwoIsRunning(string baseUrl, string basePath, int statusCode, string responseBody, string butterflyUrl)
{
- _serviceTwoBuilder = new WebHostBuilder()
+ _serviceTwoBuilder = TestHostBuilder.Create()
.UseUrls(baseUrl)
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
diff --git a/test/Ocelot.AcceptanceTests/ClaimsToDownstreamPathTests.cs b/test/Ocelot.AcceptanceTests/ClaimsToDownstreamPathTests.cs
index 2fdca76f8..1c2e98167 100644
--- a/test/Ocelot.AcceptanceTests/ClaimsToDownstreamPathTests.cs
+++ b/test/Ocelot.AcceptanceTests/ClaimsToDownstreamPathTests.cs
@@ -99,7 +99,7 @@ private void ThenTheDownstreamPathIs(string path)
private void GivenThereIsAServiceRunningOn(string url, int statusCode)
{
- _servicebuilder = new WebHostBuilder()
+ _servicebuilder = TestHostBuilder.Create()
.UseUrls(url)
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
@@ -125,7 +125,7 @@ private void GivenThereIsAServiceRunningOn(string url, int statusCode)
private async Task GivenThereIsAnIdentityServerOn(string url, string apiName, AccessTokenType tokenType, TestUser user)
{
- _identityServerBuilder = new WebHostBuilder()
+ _identityServerBuilder = TestHostBuilder.Create()
.UseUrls(url)
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
diff --git a/test/Ocelot.AcceptanceTests/ClaimsToHeadersForwardingTests.cs b/test/Ocelot.AcceptanceTests/ClaimsToHeadersForwardingTests.cs
index 0f2e5b3e3..1ca691cf2 100644
--- a/test/Ocelot.AcceptanceTests/ClaimsToHeadersForwardingTests.cs
+++ b/test/Ocelot.AcceptanceTests/ClaimsToHeadersForwardingTests.cs
@@ -119,7 +119,7 @@ private void GivenThereIsAServiceRunningOn(string url, int statusCode)
private async Task GivenThereIsAnIdentityServerOn(string url, string apiName, AccessTokenType tokenType, TestUser user)
{
- _identityServerBuilder = new WebHostBuilder()
+ _identityServerBuilder = TestHostBuilder.Create()
.UseUrls(url)
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
diff --git a/test/Ocelot.AcceptanceTests/ClaimsToQueryStringForwardingTests.cs b/test/Ocelot.AcceptanceTests/ClaimsToQueryStringForwardingTests.cs
index fb3fb241c..00c757327 100644
--- a/test/Ocelot.AcceptanceTests/ClaimsToQueryStringForwardingTests.cs
+++ b/test/Ocelot.AcceptanceTests/ClaimsToQueryStringForwardingTests.cs
@@ -174,7 +174,7 @@ private void ThenTheQueryStringIs(string queryString)
private void GivenThereIsAServiceRunningOn(string url, int statusCode)
{
- _servicebuilder = new WebHostBuilder()
+ _servicebuilder = TestHostBuilder.Create()
.UseUrls(url)
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
@@ -206,7 +206,7 @@ private void GivenThereIsAServiceRunningOn(string url, int statusCode)
private async Task GivenThereIsAnIdentityServerOn(string url, string apiName, AccessTokenType tokenType, TestUser user)
{
- _identityServerBuilder = new WebHostBuilder()
+ _identityServerBuilder = TestHostBuilder.Create()
.UseUrls(url)
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
diff --git a/test/Ocelot.AcceptanceTests/Configuration/ConfigurationInConsulTests.cs b/test/Ocelot.AcceptanceTests/Configuration/ConfigurationInConsulTests.cs
index 9c86c4363..e61fdebe3 100644
--- a/test/Ocelot.AcceptanceTests/Configuration/ConfigurationInConsulTests.cs
+++ b/test/Ocelot.AcceptanceTests/Configuration/ConfigurationInConsulTests.cs
@@ -88,8 +88,7 @@ public void Should_return_response_200_with_simple_url_when_using_jsonserialized
private void GivenOcelotIsRunningUsingConsulToStoreConfigAndJsonSerializedCache()
{
- _webHostBuilder = new WebHostBuilder()
- .UseDefaultServiceProvider(_ => _.ValidateScopes = true)
+ _webHostBuilder = TestHostBuilder.Create()
.ConfigureAppConfiguration((hostingContext, config) =>
{
config.SetBasePath(hostingContext.HostingEnvironment.ContentRootPath);
diff --git a/test/Ocelot.AcceptanceTests/DefaultVersionPolicyTests.cs b/test/Ocelot.AcceptanceTests/DefaultVersionPolicyTests.cs
index c9a1d1419..3fe2497b7 100644
--- a/test/Ocelot.AcceptanceTests/DefaultVersionPolicyTests.cs
+++ b/test/Ocelot.AcceptanceTests/DefaultVersionPolicyTests.cs
@@ -131,7 +131,7 @@ public void Should_return_ok_when_request_version_higher_receive_exact()
private static void GivenThereIsAServiceRunningOn(int port, HttpProtocols protocols)
{
var url = $"{Uri.UriSchemeHttps}://localhost:{port}";
- var builder = new WebHostBuilder()
+ var builder = TestHostBuilder.Create()
.UseUrls(url)
.UseKestrel()
.ConfigureKestrel(serverOptions =>
diff --git a/test/Ocelot.AcceptanceTests/OpenTracingTests.cs b/test/Ocelot.AcceptanceTests/OpenTracingTests.cs
index 269105e05..b37696ef3 100644
--- a/test/Ocelot.AcceptanceTests/OpenTracingTests.cs
+++ b/test/Ocelot.AcceptanceTests/OpenTracingTests.cs
@@ -161,7 +161,7 @@ private void ThenTheTracerIsCalled(FakeTracer fakeTracer)
private void GivenServiceOneIsRunning(string baseUrl, string basePath, int statusCode, string responseBody, string butterflyUrl)
{
- _serviceOneBuilder = new WebHostBuilder()
+ _serviceOneBuilder = TestHostBuilder.Create()
.UseUrls(baseUrl)
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
@@ -201,7 +201,7 @@ private void GivenServiceOneIsRunning(string baseUrl, string basePath, int statu
private void GivenFakeOpenTracing(string baseUrl)
{
- _fakeOpenTracing = new WebHostBuilder()
+ _fakeOpenTracing = TestHostBuilder.Create()
.UseUrls(baseUrl)
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
@@ -220,7 +220,7 @@ private void GivenFakeOpenTracing(string baseUrl)
private void GivenServiceTwoIsRunning(string baseUrl, string basePath, int statusCode, string responseBody, string butterflyUrl)
{
- _serviceTwoBuilder = new WebHostBuilder()
+ _serviceTwoBuilder = TestHostBuilder.Create()
.UseUrls(baseUrl)
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
diff --git a/test/Ocelot.AcceptanceTests/ServiceDiscovery/ConsulConfigurationInConsulTests.cs b/test/Ocelot.AcceptanceTests/ServiceDiscovery/ConsulConfigurationInConsulTests.cs
index d234c2ab6..60ccb0559 100644
--- a/test/Ocelot.AcceptanceTests/ServiceDiscovery/ConsulConfigurationInConsulTests.cs
+++ b/test/Ocelot.AcceptanceTests/ServiceDiscovery/ConsulConfigurationInConsulTests.cs
@@ -353,8 +353,7 @@ private void GivenTheServicesAreRegisteredWithConsul(params ServiceEntry[] servi
private void GivenOcelotIsRunningUsingConsulToStoreConfig()
{
- _webHostBuilder = new WebHostBuilder()
- .UseDefaultServiceProvider(_ => _.ValidateScopes = true)
+ _webHostBuilder = TestHostBuilder.Create()
.ConfigureAppConfiguration((hostingContext, config) =>
{
config.SetBasePath(hostingContext.HostingEnvironment.ContentRootPath);
@@ -374,7 +373,7 @@ private void GivenOcelotIsRunningUsingConsulToStoreConfig()
private Task GivenThereIsAFakeConsulServiceDiscoveryProvider(string url, string serviceName)
{
- _fakeConsulBuilder = new WebHostBuilder()
+ _fakeConsulBuilder = TestHostBuilder.Create()
.UseUrls(url)
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
@@ -449,7 +448,7 @@ public FakeConsulGetResponse(string value)
private Task GivenThereIsAServiceRunningOn(string url, string basePath, int statusCode, string responseBody)
{
- _builder = new WebHostBuilder()
+ _builder = TestHostBuilder.Create()
.UseUrls(url)
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
diff --git a/test/Ocelot.AcceptanceTests/ServiceDiscovery/ConsulServiceDiscoveryTests.cs b/test/Ocelot.AcceptanceTests/ServiceDiscovery/ConsulServiceDiscoveryTests.cs
index 6a388a5df..80d56628b 100644
--- a/test/Ocelot.AcceptanceTests/ServiceDiscovery/ConsulServiceDiscoveryTests.cs
+++ b/test/Ocelot.AcceptanceTests/ServiceDiscovery/ConsulServiceDiscoveryTests.cs
@@ -59,7 +59,7 @@ public void ShouldDiscoverServicesInConsulAndLoadBalanceByLeastConnectionWhenCon
.And(x => x.GivenThereIsAFakeConsulServiceDiscoveryProvider(DownstreamUrl(consulPort)))
.And(x => x.GivenTheServicesAreRegisteredWithConsul(serviceEntries))
.And(x => GivenThereIsAConfiguration(configuration))
- .And(x => GivenOcelotIsRunningWithServices(WithConsul, true))
+ .And(x => GivenOcelotIsRunningWithServices(WithConsul))
.When(x => WhenIGetUrlOnTheApiGatewayConcurrently("/", 50))
.Then(x => ThenAllServicesShouldHaveBeenCalledTimes(50))
.And(x => ThenAllServicesCalledRealisticAmountOfTimes(/*25*/24, /*25*/26)) // TODO Check strict assertion
@@ -84,7 +84,7 @@ public void ShouldHandleRequestToConsulForDownstreamServiceAndMakeRequest()
.And(x => x.GivenThereIsAFakeConsulServiceDiscoveryProvider(DownstreamUrl(consulPort)))
.And(x => x.GivenTheServicesAreRegisteredWithConsul(serviceEntryOne))
.And(x => GivenThereIsAConfiguration(configuration))
- .And(x => GivenOcelotIsRunningWithServices(WithConsul, true))
+ .And(x => GivenOcelotIsRunningWithServices(WithConsul))
.When(x => WhenIGetUrlOnTheApiGateway("/home"))
.Then(x => ThenTheStatusCodeShouldBe(HttpStatusCode.OK))
.And(x => ThenTheResponseBodyShouldBe("Hello from Laura"))
@@ -114,7 +114,7 @@ public void ShouldHandleRequestToConsulForDownstreamServiceAndMakeRequestWhenDyn
.And(x => x.GivenThereIsAFakeConsulServiceDiscoveryProvider(DownstreamUrl(consulPort)))
.And(x => x.GivenTheServicesAreRegisteredWithConsul(serviceEntry))
.And(x => GivenThereIsAConfiguration(configuration))
- .And(x => GivenOcelotIsRunningWithServices(WithConsul, true))
+ .And(x => GivenOcelotIsRunningWithServices(WithConsul))
.When(x => WhenIGetUrlOnTheApiGateway("/web/something"))
.Then(x => ThenTheStatusCodeShouldBe(HttpStatusCode.OK))
.And(x => ThenTheResponseBodyShouldBe("Hello from Laura"))
@@ -139,7 +139,7 @@ public void ShouldUseConsulServiceDiscoveryAndLoadBalanceRequestWhenDynamicRouti
.And(x => x.GivenThereIsAFakeConsulServiceDiscoveryProvider(DownstreamUrl(consulPort)))
.And(x => x.GivenTheServicesAreRegisteredWithConsul(serviceEntries))
.And(x => GivenThereIsAConfiguration(configuration))
- .And(x => GivenOcelotIsRunningWithServices(WithConsul, true))
+ .And(x => GivenOcelotIsRunningWithServices(WithConsul))
.When(x => WhenIGetUrlOnTheApiGatewayConcurrently($"/{serviceName}/", 50))
.Then(x => ThenAllServicesShouldHaveBeenCalledTimes(50))
.And(x => ThenAllServicesCalledRealisticAmountOfTimes(/*25*/24, /*25*/26)) // TODO Check strict assertion
@@ -164,7 +164,7 @@ public void ShouldUseAclTokenToMakeRequestToConsul()
.And(x => x.GivenThereIsAFakeConsulServiceDiscoveryProvider(DownstreamUrl(consulPort)))
.And(x => x.GivenTheServicesAreRegisteredWithConsul(serviceEntry))
.And(x => GivenThereIsAConfiguration(configuration))
- .And(x => GivenOcelotIsRunningWithServices(WithConsul, true))
+ .And(x => GivenOcelotIsRunningWithServices(WithConsul))
.When(x => WhenIGetUrlOnTheApiGateway("/home"))
.Then(x => ThenTheStatusCodeShouldBe(HttpStatusCode.OK))
.And(x => ThenTheResponseBodyShouldBe("Hello from Laura"))
@@ -187,7 +187,7 @@ public void ShouldSendRequestToServiceAfterItBecomesAvailableInConsul()
.And(x => x.GivenThereIsAFakeConsulServiceDiscoveryProvider(DownstreamUrl(consulPort)))
.And(x => x.GivenTheServicesAreRegisteredWithConsul(serviceEntries))
.And(x => GivenThereIsAConfiguration(configuration))
- .And(x => GivenOcelotIsRunningWithServices(WithConsul, true))
+ .And(x => GivenOcelotIsRunningWithServices(WithConsul))
.And(x => WhenIGetUrlOnTheApiGatewayConcurrently("/", 10))
.And(x => ThenAllServicesShouldHaveBeenCalledTimes(10))
.And(x => ThenAllServicesCalledRealisticAmountOfTimes(/*5*/4, /*5*/6)) // TODO Check strict assertion
@@ -223,7 +223,7 @@ public void ShouldPollConsulForDownstreamServiceAndMakeRequest()
.And(x => x.GivenThereIsAFakeConsulServiceDiscoveryProvider(DownstreamUrl(consulPort)))
.And(x => x.GivenTheServicesAreRegisteredWithConsul(serviceEntry))
.And(x => GivenThereIsAConfiguration(configuration))
- .And(x => GivenOcelotIsRunningWithServices(WithConsul, true))
+ .And(x => GivenOcelotIsRunningWithServices(WithConsul))
.When(x => WhenIGetUrlOnTheApiGatewayWaitingForTheResponseToBeOk("/home"))
.Then(x => ThenTheStatusCodeShouldBe(HttpStatusCode.OK))
.And(x => ThenTheResponseBodyShouldBe("Hello from Laura"))
@@ -271,7 +271,7 @@ public void ShouldUseConsulServiceDiscoveryWhenThereAreTwoUpstreamHosts(string l
.And(x => x.GivenThereIsAFakeConsulServiceDiscoveryProvider(DownstreamUrl(consulPort)))
.And(x => x.GivenTheServicesAreRegisteredWithConsul(serviceEntryUS, serviceEntryEU))
.And(x => GivenThereIsAConfiguration(configuration))
- .And(x => GivenOcelotIsRunningWithServices(WithConsul, true))
+ .And(x => GivenOcelotIsRunningWithServices(WithConsul))
.When(x => x.WhenIGetUrl(publicUrlUS, sessionCookieUS), "When I get US shop for the first time")
.Then(x => x.ThenConsulShouldHaveBeenCalledTimes(1))
.And(x => ThenTheStatusCodeShouldBe(HttpStatusCode.OK))
@@ -313,7 +313,7 @@ public void ShouldReturnServiceAddressByOverriddenServiceBuilderWhenThereIsANode
.And(x => x.GivenTheServicesAreRegisteredWithConsul(serviceEntry))
.And(x => x.GivenTheServiceNodesAreRegisteredWithConsul(serviceNode))
.And(x => GivenThereIsAConfiguration(configuration))
- .And(x => GivenOcelotIsRunningWithServices(WithConsul, true)) // default services registration results with the bug: "n1" host issue
+ .And(x => GivenOcelotIsRunningWithServices(WithConsul)) // default services registration results with the bug: "n1" host issue
.When(x => WhenIGetUrlOnTheApiGateway("/open/home"))
.Then(x => ThenTheStatusCodeShouldBe(HttpStatusCode.BadGateway))
.And(x => ThenTheResponseBodyShouldBe(""))
@@ -321,7 +321,7 @@ public void ShouldReturnServiceAddressByOverriddenServiceBuilderWhenThereIsANode
.And(x => ThenConsulNodesShouldHaveBeenCalledTimes(1))
// Override default service builder
- .Given(x => GivenOcelotIsRunningWithServices(WithConsulServiceBuilder, true))
+ .Given(x => GivenOcelotIsRunningWithServices(WithConsulServiceBuilder))
.When(x => WhenIGetUrlOnTheApiGateway("/open/home"))
.Then(x => ThenTheStatusCodeShouldBe(HttpStatusCode.OK))
.And(x => ThenTheResponseBodyShouldBe("Hello from Raman"))
@@ -368,7 +368,7 @@ public void ShouldReturnDifferentServicesWhenThereAre2SequentialRequestsToDiffer
.And(x => x.GivenThereIsAFakeConsulServiceDiscoveryProvider(DownstreamUrl(consulPort)))
.And(x => x.GivenTheServicesAreRegisteredWithConsul(service1, service2))
.And(x => GivenThereIsAConfiguration(configuration))
- .And(x => GivenOcelotIsRunningWithServices(WithConsul, true))
+ .And(x => GivenOcelotIsRunningWithServices(WithConsul))
// Step 1
.When(x => WhenIGetUrlOnTheApiGateway("/projects/api/projects"))
@@ -428,7 +428,7 @@ public void ShouldReturnDifferentServicesWhenSequentiallylyRequestingToDifferent
.And(x => x.GivenThereIsAFakeConsulServiceDiscoveryProvider(DownstreamUrl(consulPort)))
.And(x => x.GivenTheServicesAreRegisteredWithConsul(service1, service2))
.And(x => GivenThereIsAConfiguration(configuration))
- .And(x => GivenOcelotIsRunningWithServices(withAnalyzer ? WithLbAnalyzer(loadBalancer) : WithConsul, true))
+ .And(x => GivenOcelotIsRunningWithServices(withAnalyzer ? WithLbAnalyzer(loadBalancer) : WithConsul))
.When(x => WhenIDoActionMultipleTimes(50, requestToProjectsAndThenRequestToCustomersAndAssert))
.Then(x => ThenAllStatusCodesShouldBe(HttpStatusCode.OK))
.And(x => x.ThenResponsesShouldHaveBodyFromDifferentServices(ports, Bug2119ServiceNames)) // !!!
@@ -461,7 +461,7 @@ public void ShouldReturnDifferentServicesWhenConcurrentlyRequestingToDifferentSe
.And(x => x.GivenThereIsAFakeConsulServiceDiscoveryProvider(DownstreamUrl(consulPort)))
.And(x => x.GivenTheServicesAreRegisteredWithConsul(service1, service2))
.And(x => GivenThereIsAConfiguration(configuration))
- .And(x => GivenOcelotIsRunningWithServices(withAnalyzer ? WithLbAnalyzer(loadBalancer) : WithConsul, true))
+ .And(x => GivenOcelotIsRunningWithServices(withAnalyzer ? WithLbAnalyzer(loadBalancer) : WithConsul))
.When(x => WhenIGetUrlOnTheApiGatewayConcurrently(total, "/projects/api/projects", "/customers/api/customers"))
.Then(x => ThenAllStatusCodesShouldBe(HttpStatusCode.OK))
.And(x => x.ThenResponsesShouldHaveBodyFromDifferentServices(ports, Bug2119ServiceNames)) // !!!
diff --git a/test/Ocelot.AcceptanceTests/ServiceDiscovery/ConsulWebSocketTests.cs b/test/Ocelot.AcceptanceTests/ServiceDiscovery/ConsulWebSocketTests.cs
index 8ad56288e..5be6377d7 100644
--- a/test/Ocelot.AcceptanceTests/ServiceDiscovery/ConsulWebSocketTests.cs
+++ b/test/Ocelot.AcceptanceTests/ServiceDiscovery/ConsulWebSocketTests.cs
@@ -111,8 +111,7 @@ public void ShouldProxyWebsocketInputToDownstreamServiceAndUseServiceDiscoveryAn
private async Task StartFakeOcelotWithWebSocketsWithConsul()
{
- _ocelotBuilder = new WebHostBuilder()
- .UseDefaultServiceProvider(_ => _.ValidateScopes = true)
+ _ocelotBuilder = TestHostBuilder.Create()
.ConfigureServices(s =>
{
s.AddSingleton(_ocelotBuilder);
diff --git a/test/Ocelot.AcceptanceTests/ServiceDiscovery/KubernetesServiceDiscoveryTests.cs b/test/Ocelot.AcceptanceTests/ServiceDiscovery/KubernetesServiceDiscoveryTests.cs
index 87816c8ca..7350d5ba7 100644
--- a/test/Ocelot.AcceptanceTests/ServiceDiscovery/KubernetesServiceDiscoveryTests.cs
+++ b/test/Ocelot.AcceptanceTests/ServiceDiscovery/KubernetesServiceDiscoveryTests.cs
@@ -60,7 +60,7 @@ public void ShouldReturnServicesFromK8s()
this.Given(x => GivenServiceInstanceIsRunning(downstreamUrl, downstreamResponse))
.And(x => x.GivenThereIsAFakeKubernetesProvider(endpoints, serviceName, namespaces))
.And(_ => GivenThereIsAConfiguration(configuration))
- .And(_ => GivenOcelotIsRunningWithServices(WithKubernetes, true))
+ .And(_ => GivenOcelotIsRunningWithServices(WithKubernetes))
.When(_ => WhenIGetUrlOnTheApiGateway("/"))
.Then(_ => ThenTheStatusCodeShouldBe(HttpStatusCode.OK))
.And(_ => ThenTheResponseBodyShouldBe($"1:{downstreamResponse}"))
@@ -100,7 +100,7 @@ public void ShouldReturnServicesByPortNameAsDownstreamScheme(string downstreamSc
this.Given(x => GivenServiceInstanceIsRunning(downstreamUrl, nameof(ShouldReturnServicesByPortNameAsDownstreamScheme)))
.And(x => x.GivenThereIsAFakeKubernetesProvider(endpoints, serviceName, namespaces))
.And(_ => GivenThereIsAConfiguration(configuration))
- .And(_ => GivenOcelotIsRunningWithServices(WithKubernetes, true))
+ .And(_ => GivenOcelotIsRunningWithServices(WithKubernetes))
.When(_ => WhenIGetUrlOnTheApiGateway("/api/example/1"))
.Then(_ => ThenTheStatusCodeShouldBe(statusCode))
.And(_ => ThenTheResponseBodyShouldBe(downstreamScheme == "http"
@@ -176,7 +176,7 @@ public void ShouldHighlyLoadOnUnstableKubeProvider_WithRoundRobinLoadBalancing(i
var configuration = GivenKubeConfiguration(namespaces, route);
GivenMultipleServiceInstancesAreRunning(downstreamUrls, downstreamResponses);
GivenThereIsAConfiguration(configuration);
- GivenOcelotIsRunningWithServices(WithKubernetesAndRoundRobin, true);
+ GivenOcelotIsRunningWithServices(WithKubernetesAndRoundRobin);
return (endpoints, servicePorts);
}
diff --git a/test/Ocelot.AcceptanceTests/ServiceHandler.cs b/test/Ocelot.AcceptanceTests/ServiceHandler.cs
index 5996387a3..3af4be4c1 100644
--- a/test/Ocelot.AcceptanceTests/ServiceHandler.cs
+++ b/test/Ocelot.AcceptanceTests/ServiceHandler.cs
@@ -14,7 +14,7 @@ public class ServiceHandler : IDisposable
public void GivenThereIsAServiceRunningOn(string baseUrl, RequestDelegate handler)
{
- _builder = new WebHostBuilder()
+ _builder = TestHostBuilder.Create()
.UseUrls(baseUrl)
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
@@ -30,7 +30,7 @@ public void GivenThereIsAServiceRunningOn(string baseUrl, RequestDelegate handle
public void GivenThereIsAServiceRunningOn(string baseUrl, string basePath, RequestDelegate handler)
{
- _builder = new WebHostBuilder()
+ _builder = TestHostBuilder.Create()
.UseUrls(baseUrl)
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
@@ -47,7 +47,7 @@ public void GivenThereIsAServiceRunningOn(string baseUrl, string basePath, Reque
public void GivenThereIsAServiceRunningOnWithKestrelOptions(string baseUrl, string basePath, Action options, RequestDelegate handler)
{
- _builder = new WebHostBuilder()
+ _builder = TestHostBuilder.Create()
.UseUrls(baseUrl)
.UseKestrel()
.ConfigureKestrel(options ?? WithDefaultKestrelServerOptions) // !
@@ -69,7 +69,7 @@ internal void WithDefaultKestrelServerOptions(KestrelServerOptions options)
public void GivenThereIsAServiceRunningOn(string baseUrl, string basePath, string fileName, string password, int port, RequestDelegate handler)
{
- _builder = new WebHostBuilder()
+ _builder = TestHostBuilder.Create()
.UseUrls(baseUrl)
.UseKestrel(options =>
{
@@ -91,7 +91,7 @@ public void GivenThereIsAServiceRunningOn(string baseUrl, string basePath, strin
public async Task StartFakeDownstreamService(string url, Func, Task> middleware)
{
- _builder = new WebHostBuilder()
+ _builder = TestHostBuilder.Create()
.ConfigureServices(s => { }).UseKestrel()
.UseUrls(url)
.UseContentRoot(Directory.GetCurrentDirectory())
diff --git a/test/Ocelot.AcceptanceTests/Steps.cs b/test/Ocelot.AcceptanceTests/Steps.cs
index 44eb6d5c1..ec1808906 100644
--- a/test/Ocelot.AcceptanceTests/Steps.cs
+++ b/test/Ocelot.AcceptanceTests/Steps.cs
@@ -114,7 +114,7 @@ public async Task ThenConfigShouldBeWithTimeout(FileConfiguration fileConfig, in
/// Task.
public async Task StartFakeOcelotWithWebSockets()
{
- _ocelotBuilder = new WebHostBuilder();
+ _ocelotBuilder = TestHostBuilder.Create();
_ocelotBuilder.ConfigureServices(s =>
{
s.AddSingleton(_ocelotBuilder);
@@ -231,9 +231,7 @@ public void GivenOcelotIsRunning()
protected void StartOcelot(Action configureAddOcelot, string environmentName = null)
{
- _webHostBuilder = new WebHostBuilder();
-
- _webHostBuilder
+ _webHostBuilder = TestHostBuilder.Create()
.ConfigureAppConfiguration((hostingContext, config) =>
{
var env = hostingContext.HostingEnvironment;
@@ -259,9 +257,7 @@ public void ThenTheTraceHeaderIsSet(string key)
internal void GivenOcelotIsRunningUsingButterfly(string butterflyUrl)
{
- _webHostBuilder = new WebHostBuilder();
-
- _webHostBuilder
+ _webHostBuilder = TestHostBuilder.Create()
.ConfigureAppConfiguration((hostingContext, config) =>
{
config.SetBasePath(hostingContext.HostingEnvironment.ContentRootPath);
@@ -312,9 +308,7 @@ public async Task WhenIGetUrlOnTheApiGatewayWaitingForTheResponseToBeOk(string u
public void GivenOcelotIsRunningUsingJsonSerializedCache()
{
- _webHostBuilder = new WebHostBuilder();
-
- _webHostBuilder
+ _webHostBuilder = TestHostBuilder.Create()
.ConfigureAppConfiguration((hostingContext, config) =>
{
config.SetBasePath(hostingContext.HostingEnvironment.ContentRootPath);
@@ -347,9 +341,7 @@ public void GivenOcelotIsRunningUsingJsonSerializedCache()
public void GivenOcelotIsRunningWithMiddlewareBeforePipeline(Func