To create a custom service discovery implementation, implement the IServiceDiscoveryProvider interface. Your implementation must provide a GetAsync() method that returns a list of Service objects matching the DownstreamRoute.
Step 1: Implement the interface
Create a class that implements IServiceDiscoveryProvider. The constructor should accept IServiceProvider, ServiceProviderConfiguration, and DownstreamRoute.
Step 2: Configure Ocelot
In your ocelot.json, set the Type property within GlobalConfiguration.ServiceDiscoveryProvider to the name of your custom class.
Step 3: Register the provider
In your Program.cs, register a ServiceDiscoveryFinderDelegate in the DI container to handle the instantiation of your provider.
// 1. Implementation
public class MyServiceDiscoveryProvider : IServiceDiscoveryProvider
{
private readonly IServiceProvider _serviceProvider;
private readonly ServiceProviderConfiguration _config;
private readonly DownstreamRoute _downstreamRoute;
public MyServiceDiscoveryProvider(IServiceProvider serviceProvider, ServiceProviderConfiguration config, DownstreamRoute downstreamRoute)
{
_serviceProvider = serviceProvider;
_config = config;
_downstreamRoute = downstreamRoute;
}
public Task<List<Service>> GetAsync()
{
var services = new List<Service>();
// ... logic to add services matching _downstreamRoute
return services;
}
}
// 2. ocelot.json configuration
// "GlobalConfiguration": {
// "ServiceDiscoveryProvider": {
// "Type": "MyServiceDiscoveryProvider"
// }
// }
// 3. Registration in Program.cs
ServiceDiscoveryFinderDelegate serviceDiscoveryFinder = (provider, config, route)
=> new MyServiceDiscoveryProvider(provider, config, route);
builder.Services
.AddSingleton(serviceDiscoveryFinder)
.AddOcelot(builder.Configuration);