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 callback) { - _webHostBuilder = new WebHostBuilder(); - - _webHostBuilder + _webHostBuilder = TestHostBuilder.Create() .ConfigureAppConfiguration((hostingContext, config) => { config.SetBasePath(hostingContext.HostingEnvironment.ContentRootPath); @@ -374,9 +366,7 @@ public void GivenOcelotIsRunningWithSpecificHandlersRegisteredInDi() where TOne : DelegatingHandler where TWo : DelegatingHandler { - _webHostBuilder = new WebHostBuilder(); - - _webHostBuilder + _webHostBuilder = TestHostBuilder.Create() .ConfigureAppConfiguration((hostingContext, config) => { config.SetBasePath(hostingContext.HostingEnvironment.ContentRootPath); @@ -403,9 +393,7 @@ public void GivenOcelotIsRunningWithGlobalHandlersRegisteredInDi() where TOne : DelegatingHandler where TWo : DelegatingHandler { - _webHostBuilder = new WebHostBuilder(); - - _webHostBuilder + _webHostBuilder = TestHostBuilder.Create() .ConfigureAppConfiguration((hostingContext, config) => { config.SetBasePath(hostingContext.HostingEnvironment.ContentRootPath); @@ -431,9 +419,7 @@ public void GivenOcelotIsRunningWithGlobalHandlersRegisteredInDi() public void GivenOcelotIsRunningWithHandlerRegisteredInDi(bool global = false) where TOne : DelegatingHandler { - _webHostBuilder = new WebHostBuilder(); - - _webHostBuilder + _webHostBuilder = TestHostBuilder.Create() .ConfigureAppConfiguration((hostingContext, config) => { config.SetBasePath(hostingContext.HostingEnvironment.ContentRootPath); @@ -458,9 +444,7 @@ public void GivenOcelotIsRunningWithHandlerRegisteredInDi(bool global = fa public void GivenOcelotIsRunningWithGlobalHandlersRegisteredInDi(FakeDependency dependency) where TOne : DelegatingHandler { - _webHostBuilder = new WebHostBuilder(); - - _webHostBuilder + _webHostBuilder = TestHostBuilder.Create() .ConfigureAppConfiguration((hostingContext, config) => { config.SetBasePath(hostingContext.HostingEnvironment.ContentRootPath); @@ -514,9 +498,7 @@ public Task WhenIGetUrlOnTheApiGateway(string url, CookieHe public void GivenOcelotIsRunning(Action options, string authenticationProviderKey) { - _webHostBuilder = new WebHostBuilder(); - - _webHostBuilder + _webHostBuilder = TestHostBuilder.Create() .ConfigureAppConfiguration((hostingContext, config) => { config.SetBasePath(hostingContext.HostingEnvironment.ContentRootPath); @@ -550,19 +532,12 @@ public void ThenTheReasonPhraseIs(string expected) } public void GivenOcelotIsRunningWithServices(Action configureServices) - => GivenOcelotIsRunningWithServices(configureServices, null, validateScopes: false); - - public void GivenOcelotIsRunningWithServices(Action configureServices, Action configureApp) - => GivenOcelotIsRunningWithServices(configureServices, null, validateScopes: false); - - public void GivenOcelotIsRunningWithServices(Action configureServices, bool validateScopes) - => GivenOcelotIsRunningWithServices(configureServices, null, validateScopes); + => GivenOcelotIsRunningWithServices(configureServices, null); - public void GivenOcelotIsRunningWithServices(Action configureServices, Action configureApp, bool validateScopes) + public void GivenOcelotIsRunningWithServices(Action configureServices, Action configureApp/*, bool validateScopes*/) { - _webHostBuilder = new WebHostBuilder() + _webHostBuilder = TestHostBuilder.Create() // ValidateScopes = true .ConfigureAppConfiguration(WithBasicConfiguration) - .UseDefaultServiceProvider(opts => opts.ValidateScopes = validateScopes) .ConfigureServices(configureServices ?? WithAddOcelot) .Configure(configureApp ?? WithUseOcelot); _ocelotServer = new TestServer(_webHostBuilder); @@ -594,8 +569,8 @@ public void GivenOcelotIsRunning(OcelotPipelineConfiguration ocelotPipelineConfi .AddEnvironmentVariables(); var configuration = builder.Build(); - _webHostBuilder = new WebHostBuilder(); - _webHostBuilder.ConfigureServices(s => { s.AddSingleton(_webHostBuilder); }); + _webHostBuilder = TestHostBuilder.Create() + .ConfigureServices(s => { s.AddSingleton(_webHostBuilder); }); _ocelotServer = new TestServer(_webHostBuilder .UseConfiguration(configuration) @@ -655,7 +630,7 @@ public static async Task VerifyIdentityServerStarted(string url) public void GivenOcelotIsRunningWithMinimumLogLevel(Logger logger, string appsettingsFileName) { - _webHostBuilder = new WebHostBuilder() + _webHostBuilder = TestHostBuilder.Create() .UseKestrel() .ConfigureAppConfiguration((_, config) => { @@ -874,9 +849,7 @@ private async Task Fire(string url, string expectedBody, Random random) public void GivenOcelotIsRunningWithBlowingUpDiskRepo(IFileConfigurationRepository fake) { - _webHostBuilder = new WebHostBuilder(); - - _webHostBuilder + _webHostBuilder = TestHostBuilder.Create() .ConfigureAppConfiguration((hostingContext, config) => { config.SetBasePath(hostingContext.HostingEnvironment.ContentRootPath); @@ -904,9 +877,7 @@ public void TheChangeTokenShouldBeActive(bool itShouldBeActive) public void GivenOcelotIsRunningWithLogger() { - _webHostBuilder = new WebHostBuilder(); - - _webHostBuilder + _webHostBuilder = TestHostBuilder.Create() .ConfigureAppConfiguration((hostingContext, config) => { config.SetBasePath(hostingContext.HostingEnvironment.ContentRootPath); @@ -929,9 +900,7 @@ public void GivenOcelotIsRunningWithLogger() internal void GivenOcelotIsRunningUsingOpenTracing(OpenTracing.ITracer fakeTracer) { - _webHostBuilder = new WebHostBuilder(); - - _webHostBuilder + _webHostBuilder = TestHostBuilder.Create() .ConfigureAppConfiguration((hostingContext, config) => { config.SetBasePath(hostingContext.HostingEnvironment.ContentRootPath); diff --git a/test/Ocelot.Benchmarks/AllTheThingsBenchmarks.cs b/test/Ocelot.Benchmarks/AllTheThingsBenchmarks.cs index aa177df78..0350bdc56 100644 --- a/test/Ocelot.Benchmarks/AllTheThingsBenchmarks.cs +++ b/test/Ocelot.Benchmarks/AllTheThingsBenchmarks.cs @@ -77,7 +77,7 @@ public async Task Baseline() private void GivenOcelotIsRunning(string url) { - _ocelot = new WebHostBuilder() + _ocelot = TestHostBuilder.Create() .UseKestrel() .UseUrls(url) .UseContentRoot(Directory.GetCurrentDirectory()) @@ -124,7 +124,7 @@ public static void GivenThereIsAConfiguration(FileConfiguration fileConfiguratio private void GivenThereIsAServiceRunningOn(string baseUrl, string basePath, int statusCode, string responseBody) { - _service = new WebHostBuilder() + _service = TestHostBuilder.Create() .UseUrls(baseUrl) .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) diff --git a/test/Ocelot.Benchmarks/DownstreamRouteFinderMiddlewareBenchmarks.cs b/test/Ocelot.Benchmarks/DownstreamRouteFinderMiddlewareBenchmarks.cs index 95124e6bf..ad1692a6b 100644 --- a/test/Ocelot.Benchmarks/DownstreamRouteFinderMiddlewareBenchmarks.cs +++ b/test/Ocelot.Benchmarks/DownstreamRouteFinderMiddlewareBenchmarks.cs @@ -31,7 +31,7 @@ public void SetUp() var serviceCollection = new ServiceCollection(); var config = new ConfigurationRoot(new List()); var builder = new OcelotBuilder(serviceCollection, config); - var services = serviceCollection.BuildServiceProvider(); + var services = serviceCollection.BuildServiceProvider(true); var loggerFactory = services.GetService(); var drpf = services.GetService(); diff --git a/test/Ocelot.Benchmarks/ExceptionHandlerMiddlewareBenchmarks.cs b/test/Ocelot.Benchmarks/ExceptionHandlerMiddlewareBenchmarks.cs index 35e0f25b0..847589cf1 100644 --- a/test/Ocelot.Benchmarks/ExceptionHandlerMiddlewareBenchmarks.cs +++ b/test/Ocelot.Benchmarks/ExceptionHandlerMiddlewareBenchmarks.cs @@ -29,7 +29,7 @@ public void SetUp() var serviceCollection = new ServiceCollection(); var config = new ConfigurationRoot(new List()); var builder = new OcelotBuilder(serviceCollection, config); - var services = serviceCollection.BuildServiceProvider(); + var services = serviceCollection.BuildServiceProvider(true); var loggerFactory = services.GetService(); var repo = services.GetService(); diff --git a/test/Ocelot.Benchmarks/MsLoggerBenchmarks.cs b/test/Ocelot.Benchmarks/MsLoggerBenchmarks.cs index f9bada2a5..b8b53ff1b 100644 --- a/test/Ocelot.Benchmarks/MsLoggerBenchmarks.cs +++ b/test/Ocelot.Benchmarks/MsLoggerBenchmarks.cs @@ -87,7 +87,7 @@ public void Cleanup() private void GivenOcelotIsRunning(string url, LogLevel minLogLevel) { - _webHost = new WebHostBuilder() + _webHost = TestHostBuilder.Create() .UseKestrel() .UseUrls(url) .UseContentRoot(Directory.GetCurrentDirectory()) @@ -174,7 +174,7 @@ public static void GivenThereIsAConfiguration(FileConfiguration fileConfiguratio private void GivenThereIsAServiceRunningOn(string baseUrl, string basePath, int statusCode, string responseBody) { - _service = new WebHostBuilder() + _service = TestHostBuilder.Create() .UseUrls(baseUrl) .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) diff --git a/test/Ocelot.Benchmarks/Ocelot.Benchmarks.csproj b/test/Ocelot.Benchmarks/Ocelot.Benchmarks.csproj index eb906e816..e2ed9a99f 100644 --- a/test/Ocelot.Benchmarks/Ocelot.Benchmarks.csproj +++ b/test/Ocelot.Benchmarks/Ocelot.Benchmarks.csproj @@ -19,6 +19,7 @@ + diff --git a/test/Ocelot.Benchmarks/PayloadBenchmarks.cs b/test/Ocelot.Benchmarks/PayloadBenchmarks.cs index db0f8d128..aa967d16f 100644 --- a/test/Ocelot.Benchmarks/PayloadBenchmarks.cs +++ b/test/Ocelot.Benchmarks/PayloadBenchmarks.cs @@ -192,7 +192,7 @@ private static string GenerateDummyDatFile(int sizeInMb, string payloadPath) private void GivenOcelotIsRunning(string url) { - _ocelot = new WebHostBuilder() + _ocelot = TestHostBuilder.Create() .UseKestrel() .UseUrls(url) .UseContentRoot(Directory.GetCurrentDirectory()) @@ -232,7 +232,7 @@ public static void GivenThereIsAConfiguration(FileConfiguration fileConfiguratio private void GivenThereIsAServiceRunningOn(string baseUrl, string basePath, int statusCode) { - _service = new WebHostBuilder() + _service = TestHostBuilder.Create() .UseUrls(baseUrl) .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) diff --git a/test/Ocelot.Benchmarks/ResponseBenchmarks.cs b/test/Ocelot.Benchmarks/ResponseBenchmarks.cs index 458dbf65b..53788b140 100644 --- a/test/Ocelot.Benchmarks/ResponseBenchmarks.cs +++ b/test/Ocelot.Benchmarks/ResponseBenchmarks.cs @@ -194,7 +194,7 @@ private static string GenerateDummyDatFile(int sizeInMb, string payloadPath) private void GivenOcelotIsRunning(string url) { - _ocelot = new WebHostBuilder() + _ocelot = TestHostBuilder.Create() .UseKestrel() .UseUrls(url) .UseContentRoot(Directory.GetCurrentDirectory()) @@ -234,7 +234,7 @@ public static void GivenThereIsAConfiguration(FileConfiguration fileConfiguratio private void GivenThereIsAServiceRunningOn(string baseUrl, string basePath, int statusCode) { - _service = new WebHostBuilder() + _service = TestHostBuilder.Create() .UseUrls(baseUrl) .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) diff --git a/test/Ocelot.Benchmarks/SerilogBenchmarks.cs b/test/Ocelot.Benchmarks/SerilogBenchmarks.cs index 4d2ffb381..cd2adcb98 100644 --- a/test/Ocelot.Benchmarks/SerilogBenchmarks.cs +++ b/test/Ocelot.Benchmarks/SerilogBenchmarks.cs @@ -118,7 +118,7 @@ private void GivenOcelotIsRunning(string url, LogLevel minLogLevel) _ => throw new ArgumentOutOfRangeException(nameof(minLogLevel), minLogLevel, null), }; - _webHost = new WebHostBuilder() + _webHost = TestHostBuilder.Create() .UseKestrel() .UseUrls(url) .UseContentRoot(Directory.GetCurrentDirectory()) @@ -205,7 +205,7 @@ public static void GivenThereIsAConfiguration(FileConfiguration fileConfiguratio private void GivenThereIsAServiceRunningOn(string baseUrl, string basePath, int statusCode, string responseBody) { - _service = new WebHostBuilder() + _service = TestHostBuilder.Create() .UseUrls(baseUrl) .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) diff --git a/test/Ocelot.Benchmarks/Usings.cs b/test/Ocelot.Benchmarks/Usings.cs index 45cf057af..72ca281a3 100644 --- a/test/Ocelot.Benchmarks/Usings.cs +++ b/test/Ocelot.Benchmarks/Usings.cs @@ -14,3 +14,4 @@ global using BenchmarkDotNet.Diagnosers; global using BenchmarkDotNet.Validators; global using Ocelot; +global using Ocelot.Testing; diff --git a/test/Ocelot.IntegrationTests/HeaderTests.cs b/test/Ocelot.IntegrationTests/HeaderTests.cs index c114787ce..a5a2a502b 100644 --- a/test/Ocelot.IntegrationTests/HeaderTests.cs +++ b/test/Ocelot.IntegrationTests/HeaderTests.cs @@ -73,7 +73,7 @@ public async Task Should_pass_remote_ip_address_if_as_x_forwarded_for_header() private void GivenThereIsAServiceRunningOn(string url, int statusCode, string headerKey) { - _downstreamBuilder = new WebHostBuilder() + _downstreamBuilder = TestHostBuilder.Create() .UseUrls(url) .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) @@ -98,7 +98,7 @@ private void GivenThereIsAServiceRunningOn(string url, int statusCode, string he private void GivenOcelotIsRunning() { - _webHostBuilder = new WebHostBuilder() + _webHostBuilder = TestHostBuilder.Create() .UseUrls(_ocelotBaseUrl) .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) diff --git a/test/Ocelot.IntegrationTests/ThreadSafeHeadersTests.cs b/test/Ocelot.IntegrationTests/ThreadSafeHeadersTests.cs index 5c651d599..4ce82c533 100644 --- a/test/Ocelot.IntegrationTests/ThreadSafeHeadersTests.cs +++ b/test/Ocelot.IntegrationTests/ThreadSafeHeadersTests.cs @@ -64,7 +64,7 @@ public void Should_return_same_response_for_each_different_header_under_load_to_ private void GivenThereIsAServiceRunningOn(string url) { - _downstreamBuilder = new WebHostBuilder() + _downstreamBuilder = TestHostBuilder.Create() .UseUrls(url) .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) @@ -87,7 +87,7 @@ private void GivenThereIsAServiceRunningOn(string url) private void GivenOcelotIsRunning() { - _webHostBuilder = new WebHostBuilder() + _webHostBuilder = TestHostBuilder.Create() .UseUrls(_ocelotBaseUrl) .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) diff --git a/test/Ocelot.ManualTest/Ocelot.ManualTest.csproj b/test/Ocelot.ManualTest/Ocelot.ManualTest.csproj index aceeab861..a6bbc0a08 100644 --- a/test/Ocelot.ManualTest/Ocelot.ManualTest.csproj +++ b/test/Ocelot.ManualTest/Ocelot.ManualTest.csproj @@ -30,6 +30,7 @@ + diff --git a/test/Ocelot.ManualTest/Program.cs b/test/Ocelot.ManualTest/Program.cs index 54ebbda04..591d7e016 100644 --- a/test/Ocelot.ManualTest/Program.cs +++ b/test/Ocelot.ManualTest/Program.cs @@ -12,7 +12,7 @@ public class Program { public static void Main(string[] args) { - new WebHostBuilder() + TestHostBuilder.Create() .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .ConfigureAppConfiguration((hostingContext, config) => diff --git a/test/Ocelot.ManualTest/Usings.cs b/test/Ocelot.ManualTest/Usings.cs index 4aa8647a8..2fc8cee12 100644 --- a/test/Ocelot.ManualTest/Usings.cs +++ b/test/Ocelot.ManualTest/Usings.cs @@ -11,4 +11,5 @@ // Project extra global namespaces global using Ocelot; +global using Ocelot.Testing; global using System; diff --git a/test/Ocelot.Testing/TestHostBuilder.cs b/test/Ocelot.Testing/TestHostBuilder.cs new file mode 100644 index 000000000..b57d66af4 --- /dev/null +++ b/test/Ocelot.Testing/TestHostBuilder.cs @@ -0,0 +1,16 @@ +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.DependencyInjection; + +namespace Ocelot.Testing; + +public sealed class TestHostBuilder : WebHostBuilder +{ + public static IWebHostBuilder Create() + => new WebHostBuilder().UseDefaultServiceProvider(WithEnabledValidateScopes); + + public static IWebHostBuilder Create(Action configure) + => new WebHostBuilder().UseDefaultServiceProvider(configure + WithEnabledValidateScopes); + + public static void WithEnabledValidateScopes(ServiceProviderOptions options) + => options.ValidateScopes = true; +} diff --git a/test/Ocelot.UnitTests/Administration/OcelotAdministrationBuilderTests.cs b/test/Ocelot.UnitTests/Administration/OcelotAdministrationBuilderTests.cs index 15c827662..80a1cb5e2 100644 --- a/test/Ocelot.UnitTests/Administration/OcelotAdministrationBuilderTests.cs +++ b/test/Ocelot.UnitTests/Administration/OcelotAdministrationBuilderTests.cs @@ -70,7 +70,7 @@ private void WhenISetUpAdministration(Action options) private void ThenTheCorrectAdminPathIsRegitered() { - _serviceProvider = _services.BuildServiceProvider(); + _serviceProvider = _services.BuildServiceProvider(true); var path = _serviceProvider.GetService(); path.Path.ShouldBe("/administration"); } diff --git a/test/Ocelot.UnitTests/Configuration/ConfigurationCreatorTests.cs b/test/Ocelot.UnitTests/Configuration/ConfigurationCreatorTests.cs index 7b3f98a2a..d91d14a45 100644 --- a/test/Ocelot.UnitTests/Configuration/ConfigurationCreatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/ConfigurationCreatorTests.cs @@ -115,7 +115,7 @@ private void GivenTheDependenciesAreSetUp() private void WhenICreate() { - var serviceProvider = _serviceCollection.BuildServiceProvider(); + var serviceProvider = _serviceCollection.BuildServiceProvider(true); _creator = new ConfigurationCreator(_spcCreator.Object, _qosCreator.Object, _hhoCreator.Object, serviceProvider, _lboCreator.Object, _vCreator.Object, _versionPolicyCreator.Object); _result = _creator.Create(_fileConfig, _routes); } diff --git a/test/Ocelot.UnitTests/Configuration/HttpHandlerOptionsCreatorTests.cs b/test/Ocelot.UnitTests/Configuration/HttpHandlerOptionsCreatorTests.cs index 33f6d629a..924dc919d 100644 --- a/test/Ocelot.UnitTests/Configuration/HttpHandlerOptionsCreatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/HttpHandlerOptionsCreatorTests.cs @@ -18,7 +18,7 @@ public class HttpHandlerOptionsCreatorTests : UnitTest public HttpHandlerOptionsCreatorTests() { _serviceCollection = new ServiceCollection(); - _serviceProvider = _serviceCollection.BuildServiceProvider(); + _serviceProvider = _serviceCollection.BuildServiceProvider(true); _httpHandlerOptionsCreator = new HttpHandlerOptionsCreator(_serviceProvider); } @@ -210,7 +210,7 @@ private void GivenARealTracer() { var tracer = new FakeTracer(); _serviceCollection.AddSingleton(); - _serviceProvider = _serviceCollection.BuildServiceProvider(); + _serviceProvider = _serviceCollection.BuildServiceProvider(true); _httpHandlerOptionsCreator = new HttpHandlerOptionsCreator(_serviceProvider); } diff --git a/test/Ocelot.UnitTests/Configuration/Validation/FileConfigurationFluentValidatorTests.cs b/test/Ocelot.UnitTests/Configuration/Validation/FileConfigurationFluentValidatorTests.cs index 22e76fe11..6aa6a398c 100644 --- a/test/Ocelot.UnitTests/Configuration/Validation/FileConfigurationFluentValidatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/Validation/FileConfigurationFluentValidatorTests.cs @@ -31,7 +31,7 @@ public FileConfigurationFluentValidatorTests() { _services = new ServiceCollection(); _authProvider = new Mock(); - _provider = _services.BuildServiceProvider(); + _provider = _services.BuildServiceProvider(true); // TODO Replace with mocks _configurationValidator = new FileConfigurationFluentValidator(_provider, new RouteFluentValidator(_authProvider.Object, new HostAndPortValidator(), new FileQoSOptionsFluentValidator(_provider)), new FileGlobalConfigurationFluentValidator(new FileQoSOptionsFluentValidator(_provider))); @@ -972,7 +972,7 @@ private void GivenAQoSHandler() { DelegatingHandler Del(DownstreamRoute a, IHttpContextAccessor b, IOcelotLoggerFactory c) => new FakeDelegatingHandler(); _services.AddSingleton((QosDelegatingHandlerDelegate)Del); - _provider = _services.BuildServiceProvider(); + _provider = _services.BuildServiceProvider(true); _configurationValidator = new FileConfigurationFluentValidator(_provider, new RouteFluentValidator(_authProvider.Object, new HostAndPortValidator(), new FileQoSOptionsFluentValidator(_provider)), new FileGlobalConfigurationFluentValidator(new FileQoSOptionsFluentValidator(_provider))); } @@ -980,7 +980,7 @@ private void GivenAServiceDiscoveryHandler() { ServiceDiscoveryFinderDelegate del = (a, b, c) => new FakeServiceDiscoveryProvider(); _services.AddSingleton(del); - _provider = _services.BuildServiceProvider(); + _provider = _services.BuildServiceProvider(true); _configurationValidator = new FileConfigurationFluentValidator(_provider, new RouteFluentValidator(_authProvider.Object, new HostAndPortValidator(), new FileQoSOptionsFluentValidator(_provider)), new FileGlobalConfigurationFluentValidator(new FileQoSOptionsFluentValidator(_provider))); } diff --git a/test/Ocelot.UnitTests/Configuration/Validation/FileQoSOptionsFluentValidatorTests.cs b/test/Ocelot.UnitTests/Configuration/Validation/FileQoSOptionsFluentValidatorTests.cs index 84d041e23..591a5a0c2 100644 --- a/test/Ocelot.UnitTests/Configuration/Validation/FileQoSOptionsFluentValidatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/Validation/FileQoSOptionsFluentValidatorTests.cs @@ -19,7 +19,7 @@ public class FileQoSOptionsFluentValidatorTests : UnitTest public FileQoSOptionsFluentValidatorTests() { _services = new ServiceCollection(); - var provider = _services.BuildServiceProvider(); + var provider = _services.BuildServiceProvider(true); _validator = new FileQoSOptionsFluentValidator(provider); } @@ -78,7 +78,7 @@ private void GivenAQosDelegate() { DelegatingHandler Fake(DownstreamRoute a, IHttpContextAccessor b, IOcelotLoggerFactory c) => null; _services.AddSingleton((QosDelegatingHandlerDelegate)Fake); - var provider = _services.BuildServiceProvider(); + var provider = _services.BuildServiceProvider(true); _validator = new FileQoSOptionsFluentValidator(provider); } diff --git a/test/Ocelot.UnitTests/Consul/ConsulTests.cs b/test/Ocelot.UnitTests/Consul/ConsulTests.cs index fff9eaf91..b6a38fc6d 100644 --- a/test/Ocelot.UnitTests/Consul/ConsulTests.cs +++ b/test/Ocelot.UnitTests/Consul/ConsulTests.cs @@ -185,7 +185,7 @@ private void ThenTheLoggerHasBeenCalledCorrectlyWithValidationWarning() private void GivenThereIsAFakeConsulServiceDiscoveryProvider([CallerMemberName] string serviceName = "test") { - _fakeConsulBuilder = new WebHostBuilder() + _fakeConsulBuilder = TestHostBuilder.Create() .UseUrls(_fakeConsulServiceDiscoveryUrl) .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) diff --git a/test/Ocelot.UnitTests/DependencyInjection/OcelotBuilderTests.cs b/test/Ocelot.UnitTests/DependencyInjection/OcelotBuilderTests.cs index 933578ccb..bbe7342e9 100644 --- a/test/Ocelot.UnitTests/DependencyInjection/OcelotBuilderTests.cs +++ b/test/Ocelot.UnitTests/DependencyInjection/OcelotBuilderTests.cs @@ -211,16 +211,16 @@ public void Should_add_custom_load_balancer_creators() [Fact] public void Should_use_default_mvc_builder() { - this.Given(x => x.WhenISetUpOcelotServicesWithoutConfig()) - .Then(x => CstorShouldUseDefaultBuilderToInitMvcCoreBuilder()) - .BDDfy(); + WhenISetUpOcelotServicesWithoutConfig(); + CstorShouldUseDefaultBuilderToInitMvcCoreBuilder(); } private void CstorShouldUseDefaultBuilderToInitMvcCoreBuilder() { _ocelotBuilder.ShouldNotBeNull(); _ocelotBuilder.MvcCoreBuilder.ShouldNotBeNull(); - _serviceProvider = _services.BuildServiceProvider(); + _serviceProvider = _services.BuildServiceProvider(true); + using IServiceScope scope = _serviceProvider.CreateScope(); // .AddMvcCore() _serviceProvider.GetServices>() @@ -253,7 +253,7 @@ private void CstorShouldUseDefaultBuilderToInitMvcCoreBuilder() .ShouldNotBeNull().ShouldBeOfType(); // .AddAuthorization() - _serviceProvider.GetService() + scope.ServiceProvider.GetService() .ShouldNotBeNull().ShouldBeOfType(); _serviceProvider.GetService() .ShouldNotBeNull() @@ -333,7 +333,7 @@ private void CstorShouldUseCustomBuilderToInitMvcCoreBuilder() _ocelotBuilder.ShouldNotBeNull(); _ocelotBuilder.MvcCoreBuilder.ShouldNotBeNull(); - _serviceProvider = _services.BuildServiceProvider(); + _serviceProvider = _services.BuildServiceProvider(true); // .AddMvcCore() _serviceProvider.GetServices>() @@ -414,7 +414,7 @@ private void AddTypeSpecificTransientDelegatingHandler(Type type) private void ThenTheProviderIsRegisteredAndReturnsHandlers() { - _serviceProvider = _services.BuildServiceProvider(); + _serviceProvider = _services.BuildServiceProvider(true); var handlers = _serviceProvider.GetServices().ToList(); handlers[0].DelegatingHandler.ShouldBeOfType(); handlers[1].DelegatingHandler.ShouldBeOfType(); @@ -422,7 +422,7 @@ private void ThenTheProviderIsRegisteredAndReturnsHandlers() private void ThenTheProviderIsRegisteredAndReturnsSpecificHandlers() { - _serviceProvider = _services.BuildServiceProvider(); + _serviceProvider = _services.BuildServiceProvider(true); var handlers = _serviceProvider.GetServices().ToList(); handlers[0].ShouldBeOfType(); handlers[1].ShouldBeOfType(); @@ -430,7 +430,7 @@ private void ThenTheProviderIsRegisteredAndReturnsSpecificHandlers() private void ThenTheProviderIsRegisteredAndReturnsSpecificAggregators() { - _serviceProvider = _services.BuildServiceProvider(); + _serviceProvider = _services.BuildServiceProvider(true); var handlers = _serviceProvider.GetServices().ToList(); handlers[0].ShouldBeOfType(); handlers[1].ShouldBeOfType(); @@ -438,7 +438,7 @@ private void ThenTheProviderIsRegisteredAndReturnsSpecificAggregators private void ThenTheProviderIsRegisteredAndReturnsBothBuiltInAndCustomLoadBalancerCreators() { - _serviceProvider = _services.BuildServiceProvider(); + _serviceProvider = _services.BuildServiceProvider(true); var creators = _serviceProvider.GetServices().ToList(); creators.Count(c => c.GetType() == typeof(NoLoadBalancerCreator)).ShouldBe(1); creators.Count(c => c.GetType() == typeof(RoundRobinCreator)).ShouldBe(1); @@ -472,7 +472,7 @@ private void ThenAnOcelotBuilderIsReturned() private void ThenTheIPlaceholderInstanceIsReplaced() { - _serviceProvider = _services.BuildServiceProvider(); + _serviceProvider = _services.BuildServiceProvider(true); var placeholders = _serviceProvider.GetService(); placeholders.ShouldBeOfType(); } @@ -505,7 +505,7 @@ private void WhenIAccessLoggerFactory() { try { - _serviceProvider = _services.BuildServiceProvider(); + _serviceProvider = _services.BuildServiceProvider(true); var logger = _serviceProvider.GetService(); logger.ShouldNotBeNull(); } @@ -519,7 +519,7 @@ private void WhenIValidateScopes() { try { - _serviceProvider = _services.BuildServiceProvider(new ServiceProviderOptions { ValidateScopes = true }); + _serviceProvider = _services.BuildServiceProvider(true); } catch (Exception e) { diff --git a/test/Ocelot.UnitTests/DownstreamRouteFinder/DownstreamRouteProviderFactoryTests.cs b/test/Ocelot.UnitTests/DownstreamRouteFinder/DownstreamRouteProviderFactoryTests.cs index 2eb2a092b..1bccdbb2e 100644 --- a/test/Ocelot.UnitTests/DownstreamRouteFinder/DownstreamRouteProviderFactoryTests.cs +++ b/test/Ocelot.UnitTests/DownstreamRouteFinder/DownstreamRouteProviderFactoryTests.cs @@ -28,7 +28,7 @@ public DownstreamRouteProviderFactoryTests() services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); - var provider = services.BuildServiceProvider(); + var provider = services.BuildServiceProvider(true); _logger = new Mock(); _loggerFactory = new Mock(); _loggerFactory.Setup(x => x.CreateLogger()).Returns(_logger.Object); diff --git a/test/Ocelot.UnitTests/Eureka/EurekaMiddlewareConfigurationProviderTests.cs b/test/Ocelot.UnitTests/Eureka/EurekaMiddlewareConfigurationProviderTests.cs index f020707be..266ae3b50 100644 --- a/test/Ocelot.UnitTests/Eureka/EurekaMiddlewareConfigurationProviderTests.cs +++ b/test/Ocelot.UnitTests/Eureka/EurekaMiddlewareConfigurationProviderTests.cs @@ -19,7 +19,7 @@ public void ShouldNotBuild() .Returns(new OkResponse(new InternalConfiguration(null, null, null, null, null, null, null, null, null, null))); var services = new ServiceCollection(); services.AddSingleton(configRepo.Object); - var sp = services.BuildServiceProvider(); + var sp = services.BuildServiceProvider(true); var provider = EurekaMiddlewareConfigurationProvider.Get(new ApplicationBuilder(sp)); provider.Status.ShouldBe(TaskStatus.RanToCompletion); } @@ -35,7 +35,7 @@ public void ShouldBuild() var services = new ServiceCollection(); services.AddSingleton(configRepo.Object); services.AddSingleton(client.Object); - var sp = services.BuildServiceProvider(); + var sp = services.BuildServiceProvider(true); var provider = EurekaMiddlewareConfigurationProvider.Get(new ApplicationBuilder(sp)); provider.Status.ShouldBe(TaskStatus.RanToCompletion); } diff --git a/test/Ocelot.UnitTests/Eureka/EurekaProviderFactoryTests.cs b/test/Ocelot.UnitTests/Eureka/EurekaProviderFactoryTests.cs index c41f6bc62..39af5432d 100644 --- a/test/Ocelot.UnitTests/Eureka/EurekaProviderFactoryTests.cs +++ b/test/Ocelot.UnitTests/Eureka/EurekaProviderFactoryTests.cs @@ -11,7 +11,7 @@ public class EurekaProviderFactoryTests public void should_not_get() { var config = new ServiceProviderConfigurationBuilder().Build(); - var sp = new ServiceCollection().BuildServiceProvider(); + var sp = new ServiceCollection().BuildServiceProvider(true); Should.Throw(() => EurekaProviderFactory.Get(sp, config, null)); } @@ -23,7 +23,7 @@ public void should_get() var client = new Mock(); var services = new ServiceCollection(); services.AddSingleton(client.Object); - var sp = services.BuildServiceProvider(); + var sp = services.BuildServiceProvider(true); var route = new DownstreamRouteBuilder() .WithServiceName(string.Empty) .Build(); diff --git a/test/Ocelot.UnitTests/Eureka/OcelotBuilderExtensionsTests.cs b/test/Ocelot.UnitTests/Eureka/OcelotBuilderExtensionsTests.cs new file mode 100644 index 000000000..586e64df5 --- /dev/null +++ b/test/Ocelot.UnitTests/Eureka/OcelotBuilderExtensionsTests.cs @@ -0,0 +1,76 @@ +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Ocelot.DependencyInjection; +using Ocelot.Middleware; +using Ocelot.Provider.Eureka; +using Ocelot.ServiceDiscovery; +using Steeltoe.Common.Discovery; +using Steeltoe.Common.Http.Discovery; +using System.Reflection; + +namespace Ocelot.UnitTests.Eureka; + +public sealed class OcelotBuilderExtensionsTests : UnitTest +{ + private readonly IServiceCollection _services; + private readonly IConfiguration _configRoot; + private IOcelotBuilder _ocelotBuilder; + + public OcelotBuilderExtensionsTests() + { + _configRoot = new ConfigurationRoot(new List()); + _services = new ServiceCollection(); + _services.AddSingleton(GetHostingEnvironment()); + _services.AddSingleton(_configRoot); + } + + private static IWebHostEnvironment GetHostingEnvironment() + { + var environment = new Mock(); + environment.Setup(e => e.ApplicationName) + .Returns(typeof(OcelotBuilderExtensionsTests).GetTypeInfo().Assembly.GetName().Name); + return environment.Object; + } + + [Fact] + [Trait("PR", "734")] + [Trait("Feat", "324, 844")] + public void AddEureka_NoExceptions_ShouldSetUpEureka() + { + // Arrange + var addOcelot = () => _ocelotBuilder = _services.AddOcelot(_configRoot); + addOcelot.ShouldNotThrow(); + + // Act + var addEureka = () => _ocelotBuilder.AddEureka(); + + // Assert + addEureka.ShouldNotThrow(); + } + + [Fact] + [Trait("PR", "734")] + [Trait("Feat", "324, 844")] + public void AddEureka_DefaultServices_HappyPath() + { + // Arrange, Act + _ocelotBuilder = _services.AddOcelot(_configRoot).AddEureka(); + + // Assert: AddDiscoveryClient + var descriptor = _services.SingleOrDefault(Of).ShouldNotBeNull(); + descriptor.Lifetime.ShouldBe(ServiceLifetime.Transient); + descriptor = _services.SingleOrDefault(Of).ShouldNotBeNull(); + descriptor.Lifetime.ShouldBe(ServiceLifetime.Singleton); + + // Assert + descriptor = _services.SingleOrDefault(Of).ShouldNotBeNull(); + descriptor.Lifetime.ShouldBe(ServiceLifetime.Singleton); + descriptor = _services.SingleOrDefault(Of).ShouldNotBeNull(); + descriptor.Lifetime.ShouldBe(ServiceLifetime.Singleton); + } + + private static bool Of(ServiceDescriptor descriptor) + where TType : class + => descriptor.ServiceType.Equals(typeof(TType)); +} diff --git a/test/Ocelot.UnitTests/Eureka/OcelotPipelineExtensionsTests.cs b/test/Ocelot.UnitTests/Eureka/OcelotPipelineExtensionsTests.cs deleted file mode 100644 index a1d92d4a3..000000000 --- a/test/Ocelot.UnitTests/Eureka/OcelotPipelineExtensionsTests.cs +++ /dev/null @@ -1,59 +0,0 @@ -// using Microsoft.Extensions.Configuration; -// using Microsoft.Extensions.DependencyInjection; -// using Ocelot.DependencyInjection; -// using Ocelot.Middleware; -// using Ocelot.Middleware.Pipeline; -// using Steeltoe.Discovery.Client; -// using Shouldly; -// using Steeltoe.Common.Discovery; -// using Steeltoe.Discovery.Eureka; -// using TestStack.BDDfy; -// using Xunit; - -//namespace Ocelot.UnitTests.Eureka -//{ -// public class OcelotPipelineExtensionsTests -// { -// private OcelotPipelineBuilder _builder; -// private OcelotRequestDelegate _handlers; - -// [Fact] -// public void should_set_up_pipeline() -// { -// this.Given(_ => GivenTheDepedenciesAreSetUp()) -// .When(_ => WhenIBuild()) -// .Then(_ => ThenThePipelineIsBuilt()) -// .BDDfy(); -// } - -// private void ThenThePipelineIsBuilt() -// { -// _handlers.ShouldNotBeNull(); -// } - -// private void WhenIBuild() -// { -// _handlers = _builder.BuildOcelotPipeline(new OcelotPipelineConfiguration()); -// } - -// private void GivenTheDepedenciesAreSetUp() -// { -// IConfigurationBuilder test = new ConfigurationBuilder(); -// var root = test.Build(); -// var services = new ServiceCollection(); -// services.AddSingleton(root); -// services.AddDiscoveryClient(new DiscoveryOptions -// { -// ClientType = DiscoveryClientType.EUREKA, -// ClientOptions = new EurekaClientOptions() -// { -// ShouldFetchRegistry = false, -// ShouldRegisterWithEureka = false -// } -// }); -// services.AddOcelot(); -// var provider = services.BuildServiceProvider(); -// _builder = new OcelotPipelineBuilder(provider); -// } -// } -//} diff --git a/test/Ocelot.UnitTests/Kubernetes/KubeTests.cs b/test/Ocelot.UnitTests/Kubernetes/KubeTests.cs index 1e399e0c8..d6c13f60d 100644 --- a/test/Ocelot.UnitTests/Kubernetes/KubeTests.cs +++ b/test/Ocelot.UnitTests/Kubernetes/KubeTests.cs @@ -168,7 +168,7 @@ Task ProcessKubernetesRequest(HttpContext context) return Task.CompletedTask; } - var host = new WebHostBuilder() + var host = TestHostBuilder.Create() .UseUrls(url) .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) diff --git a/test/Ocelot.UnitTests/Kubernetes/KubernetesProviderFactoryTests.cs b/test/Ocelot.UnitTests/Kubernetes/KubernetesProviderFactoryTests.cs index dd8ad516e..949d87fe4 100644 --- a/test/Ocelot.UnitTests/Kubernetes/KubernetesProviderFactoryTests.cs +++ b/test/Ocelot.UnitTests/Kubernetes/KubernetesProviderFactoryTests.cs @@ -34,7 +34,7 @@ public void CreateProvider_IKubeApiClientHasOriginalLifetimeWithEnabledScopesVal .Returns(Mock.Of()); var descriptor = _builder.Services.First(x => x.ServiceType == typeof(IKubeApiClient)); _builder.Services.Replace(ServiceDescriptor.Describe(descriptor.ServiceType, _ => kubeClient.Object, descriptor.Lifetime)); - var serviceProvider = _builder.Services.BuildServiceProvider(validateScopes: true); + var serviceProvider = _builder.Services.BuildServiceProvider(true); var config = GivenServiceProvider(providerType.Name); var route = GivenRoute(); @@ -58,7 +58,7 @@ public void CreateProvider_IKubeApiClientHasScopedLifetimeWithEnabledScopesValid // Arrange var descriptor = ServiceDescriptor.Describe(typeof(IKubeApiClient), _ => Mock.Of(), ServiceLifetime.Scoped); _builder.Services.Replace(descriptor); - var serviceProvider = _builder.Services.BuildServiceProvider(validateScopes: true); + var serviceProvider = _builder.Services.BuildServiceProvider(true); var config = GivenServiceProvider(providerType); var route = GivenRoute(); diff --git a/test/Ocelot.UnitTests/Kubernetes/OcelotBuilderExtensionsTests.cs b/test/Ocelot.UnitTests/Kubernetes/OcelotBuilderExtensionsTests.cs index 09524ff95..43e90d7de 100644 --- a/test/Ocelot.UnitTests/Kubernetes/OcelotBuilderExtensionsTests.cs +++ b/test/Ocelot.UnitTests/Kubernetes/OcelotBuilderExtensionsTests.cs @@ -56,16 +56,20 @@ public void AddKubernetes_DefaultServices_HappyPath() _ocelotBuilder = _services.AddOcelot(_configRoot).AddKubernetes(); // Assert - var descriptor = _services.SingleOrDefault(sd => sd.ServiceType == typeof(IKubeApiClient)).ShouldNotBeNull(); + var descriptor = _services.SingleOrDefault(Of).ShouldNotBeNull(); descriptor.Lifetime.ShouldBe(ServiceLifetime.Singleton); // 2180 scenario - descriptor = _services.SingleOrDefault(sd => sd.ServiceType == typeof(ServiceDiscoveryFinderDelegate)).ShouldNotBeNull(); + descriptor = _services.SingleOrDefault(Of).ShouldNotBeNull(); descriptor.Lifetime.ShouldBe(ServiceLifetime.Singleton); - descriptor = _services.SingleOrDefault(sd => sd.ServiceType == typeof(IKubeServiceBuilder)).ShouldNotBeNull(); + descriptor = _services.SingleOrDefault(Of).ShouldNotBeNull(); descriptor.Lifetime.ShouldBe(ServiceLifetime.Singleton); - descriptor = _services.SingleOrDefault(sd => sd.ServiceType == typeof(IKubeServiceCreator)).ShouldNotBeNull(); + descriptor = _services.SingleOrDefault(Of).ShouldNotBeNull(); descriptor.Lifetime.ShouldBe(ServiceLifetime.Singleton); } + + private static bool Of(ServiceDescriptor descriptor) + where TType : class + => descriptor.ServiceType.Equals(typeof(TType)); } diff --git a/test/Ocelot.UnitTests/Logging/OcelotDiagnosticListenerTests.cs b/test/Ocelot.UnitTests/Logging/OcelotDiagnosticListenerTests.cs index 94d3da1c7..18a75488a 100644 --- a/test/Ocelot.UnitTests/Logging/OcelotDiagnosticListenerTests.cs +++ b/test/Ocelot.UnitTests/Logging/OcelotDiagnosticListenerTests.cs @@ -21,7 +21,7 @@ public OcelotDiagnosticListenerTests() _factory = new Mock(); _logger = new Mock(); _serviceCollection = new ServiceCollection(); - _serviceProvider = _serviceCollection.BuildServiceProvider(); + _serviceProvider = _serviceCollection.BuildServiceProvider(true); _factory.Setup(x => x.CreateLogger()).Returns(_logger.Object); _listener = new OcelotDiagnosticListener(_factory.Object, _serviceProvider); } diff --git a/test/Ocelot.UnitTests/Middleware/OcelotPipelineExtensionsTests.cs b/test/Ocelot.UnitTests/Middleware/OcelotPipelineExtensionsTests.cs index 7d2e4b75a..8ef5eacee 100644 --- a/test/Ocelot.UnitTests/Middleware/OcelotPipelineExtensionsTests.cs +++ b/test/Ocelot.UnitTests/Middleware/OcelotPipelineExtensionsTests.cs @@ -66,7 +66,7 @@ private void GivenTheDepedenciesAreSetUp() var services = new ServiceCollection(); services.AddSingleton(root); services.AddOcelot(); - var provider = services.BuildServiceProvider(); + var provider = services.BuildServiceProvider(true); _builder = new ApplicationBuilder(provider); } } diff --git a/test/Ocelot.UnitTests/Middleware/OcelotPiplineBuilderTests.cs b/test/Ocelot.UnitTests/Middleware/OcelotPiplineBuilderTests.cs index 2948b70a6..c85e928e3 100644 --- a/test/Ocelot.UnitTests/Middleware/OcelotPiplineBuilderTests.cs +++ b/test/Ocelot.UnitTests/Middleware/OcelotPiplineBuilderTests.cs @@ -56,7 +56,7 @@ public void should_build_func() private void WhenIUseAGeneric() { - var provider = _services.BuildServiceProvider(); + var provider = _services.BuildServiceProvider(true); IApplicationBuilder builder = new ApplicationBuilder(provider); builder = builder.UseMiddleware(); var del = builder.Build(); @@ -71,7 +71,7 @@ private void ThenTheGenericIsInThePipeline() private void WhenIUseAFunc() { _counter = 0; - var provider = _services.BuildServiceProvider(); + var provider = _services.BuildServiceProvider(true); IApplicationBuilder builder = new ApplicationBuilder(provider); builder = builder.Use(async (ctx, next) => { @@ -91,7 +91,7 @@ private void ThenTheFuncIsInThePipeline() [Fact] public void Middleware_Multi_Parameters_Invoke() { - var provider = _services.BuildServiceProvider(); + var provider = _services.BuildServiceProvider(true); IApplicationBuilder builder = new ApplicationBuilder(provider); builder = builder.UseMiddleware(); var del = builder.Build(); diff --git a/test/Ocelot.UnitTests/Multiplexing/DefinedAggregatorProviderTests.cs b/test/Ocelot.UnitTests/Multiplexing/DefinedAggregatorProviderTests.cs index 7a1c8e914..fd7347d8b 100644 --- a/test/Ocelot.UnitTests/Multiplexing/DefinedAggregatorProviderTests.cs +++ b/test/Ocelot.UnitTests/Multiplexing/DefinedAggregatorProviderTests.cs @@ -45,7 +45,7 @@ private void GivenDefinedAggregator() { var serviceCollection = new ServiceCollection(); serviceCollection.AddSingleton(); - var services = serviceCollection.BuildServiceProvider(); + var services = serviceCollection.BuildServiceProvider(true); _provider = new ServiceLocatorDefinedAggregatorProvider(services); } @@ -59,7 +59,7 @@ private void ThenTheAggregatorIsReturned() private void GivenNoDefinedAggregator() { var serviceCollection = new ServiceCollection(); - var services = serviceCollection.BuildServiceProvider(); + var services = serviceCollection.BuildServiceProvider(true); _provider = new ServiceLocatorDefinedAggregatorProvider(services); } diff --git a/test/Ocelot.UnitTests/Multiplexing/MultiplexingMiddlewareTests.cs b/test/Ocelot.UnitTests/Multiplexing/MultiplexingMiddlewareTests.cs index acff4ae9a..5f76a28e8 100644 --- a/test/Ocelot.UnitTests/Multiplexing/MultiplexingMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Multiplexing/MultiplexingMiddlewareTests.cs @@ -80,7 +80,7 @@ public async Task CreateThreadContextAsync_CopyUser_ToTarget() [Trait("Bug", "1396")] public async Task Invoke_ContextUser_ForwardedToDownstreamContext() { - // Setup + // Create HttpContext actualContext = null; _middleware = new MultiplexingMiddleware(NextMe, loggerFactory.Object, factory.Object); Task NextMe(HttpContext context) diff --git a/test/Ocelot.UnitTests/Polly/OcelotBuilderExtensionsTests.cs b/test/Ocelot.UnitTests/Polly/OcelotBuilderExtensionsTests.cs index 5dffec17f..34687742a 100644 --- a/test/Ocelot.UnitTests/Polly/OcelotBuilderExtensionsTests.cs +++ b/test/Ocelot.UnitTests/Polly/OcelotBuilderExtensionsTests.cs @@ -31,7 +31,7 @@ public void Should_build() services .AddOcelot(configuration) .AddPolly(); - var provider = services.BuildServiceProvider(); + var provider = services.BuildServiceProvider(true); var handler = provider.GetService(); handler.ShouldNotBeNull(); diff --git a/test/Ocelot.UnitTests/Requester/DelegatingHandlerHandlerProviderFactoryTests.cs b/test/Ocelot.UnitTests/Requester/DelegatingHandlerHandlerProviderFactoryTests.cs index dde971d69..d4a75b183 100644 --- a/test/Ocelot.UnitTests/Requester/DelegatingHandlerHandlerProviderFactoryTests.cs +++ b/test/Ocelot.UnitTests/Requester/DelegatingHandlerHandlerProviderFactoryTests.cs @@ -430,7 +430,7 @@ private void GivenTheServiceProviderReturnsSpecificDelegatingHandlers GivenTheFactoryReturns(new List>())) .And(x => GivenAMessageInvokerPool()) .And(x => GivenARequest(route)) - .When(x => WhenICallTheClient("http://www.bbc.co.uk")) + .When(x => WhenICallTheClient("http://www.google.com/")) .Then(x => ThenTheDangerousAcceptAnyServerCertificateValidatorWarningIsLogged()) .BDDfy(); } @@ -168,7 +168,7 @@ private void ThenTheCookieIsSet() private void GivenADownstreamService() { var count = 0; - _host = new WebHostBuilder() + _host = TestHostBuilder.Create() .UseUrls("http://localhost:5003") .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) diff --git a/test/Ocelot.UnitTests/Requester/QoSFactoryTests.cs b/test/Ocelot.UnitTests/Requester/QoSFactoryTests.cs index a6a69c28f..390f62ccb 100644 --- a/test/Ocelot.UnitTests/Requester/QoSFactoryTests.cs +++ b/test/Ocelot.UnitTests/Requester/QoSFactoryTests.cs @@ -20,7 +20,7 @@ public QoSFactoryTests() _services = new ServiceCollection(); _loggerFactory = new Mock(); _contextAccessor = new Mock(); - var provider = _services.BuildServiceProvider(); + var provider = _services.BuildServiceProvider(true); _factory = new QoSFactory(provider, _contextAccessor.Object, _loggerFactory.Object); } @@ -39,7 +39,7 @@ public void should_return_handler() _services = new ServiceCollection(); DelegatingHandler QosDelegatingHandlerDelegate(DownstreamRoute a, IHttpContextAccessor b, IOcelotLoggerFactory c) => new FakeDelegatingHandler(); _services.AddSingleton(QosDelegatingHandlerDelegate); - var provider = _services.BuildServiceProvider(); + var provider = _services.BuildServiceProvider(true); _factory = new QoSFactory(provider, _contextAccessor.Object, _loggerFactory.Object); var downstreamRoute = new DownstreamRouteBuilder().Build(); var handler = _factory.Get(downstreamRoute); diff --git a/test/Ocelot.UnitTests/Requester/TracingHandlerFactoryTests.cs b/test/Ocelot.UnitTests/Requester/TracingHandlerFactoryTests.cs index 10b93ce1c..5446e867f 100644 --- a/test/Ocelot.UnitTests/Requester/TracingHandlerFactoryTests.cs +++ b/test/Ocelot.UnitTests/Requester/TracingHandlerFactoryTests.cs @@ -18,7 +18,7 @@ public TracingHandlerFactoryTests() _tracer = new Mock(); _serviceCollection = new ServiceCollection(); _serviceCollection.AddSingleton(_tracer.Object); - _serviceProvider = _serviceCollection.BuildServiceProvider(); + _serviceProvider = _serviceCollection.BuildServiceProvider(true); _repo = new Mock(); _factory = new TracingHandlerFactory(_serviceProvider, _repo.Object); } diff --git a/test/Ocelot.UnitTests/ServiceDiscovery/ServiceDiscoveryProviderFactoryTests.cs b/test/Ocelot.UnitTests/ServiceDiscovery/ServiceDiscoveryProviderFactoryTests.cs index 8fc8fc8cb..88eaf27f6 100644 --- a/test/Ocelot.UnitTests/ServiceDiscovery/ServiceDiscoveryProviderFactoryTests.cs +++ b/test/Ocelot.UnitTests/ServiceDiscovery/ServiceDiscoveryProviderFactoryTests.cs @@ -27,7 +27,7 @@ public ServiceDiscoveryProviderFactoryTests() _loggerFactory = new Mock(); _logger = new Mock(); _collection = new ServiceCollection(); - _provider = _collection.BuildServiceProvider(); + _provider = _collection.BuildServiceProvider(true); _factory = new ServiceDiscoveryProviderFactory(_loggerFactory.Object, _provider); _loggerFactory.Setup(x => x.CreateLogger()) @@ -168,7 +168,7 @@ private void GivenAFakeDelegate() { ServiceDiscoveryFinderDelegate fake = (provider, config, name) => new Fake(); _collection.AddSingleton(fake); - _provider = _collection.BuildServiceProvider(); + _provider = _collection.BuildServiceProvider(true); _factory = new ServiceDiscoveryProviderFactory(_loggerFactory.Object, _provider); } @@ -179,7 +179,7 @@ private void GivenKubernetesProvider() .AddSingleton(KubernetesProviderFactory.Get) .AddSingleton(k8sClient.Object) .AddSingleton(_loggerFactory.Object); - _provider = _collection.BuildServiceProvider(); + _provider = _collection.BuildServiceProvider(true); _factory = new ServiceDiscoveryProviderFactory(_loggerFactory.Object, _provider); } diff --git a/test/Ocelot.UnitTests/Usings.cs b/test/Ocelot.UnitTests/Usings.cs index 6eb9a3d7b..9648f6280 100644 --- a/test/Ocelot.UnitTests/Usings.cs +++ b/test/Ocelot.UnitTests/Usings.cs @@ -10,6 +10,7 @@ // Project extra global namespaces global using Moq; global using Ocelot; +global using Ocelot.Testing; global using Shouldly; global using System.Net; global using TestStack.BDDfy;