1

Using ASP.NET Core 3.1 I am adding a SitemapMiddleware on Startup's Configure method:

public void Configure(IApplicationBuilder builder, IWebHostEnvironment environment) {
  builder.UseSitemap();
}

Where the UseSitemap extension is:

public static class SitemapMiddlewareExtensions {
  public static IApplicationBuilder UseSitemap(this IApplicationBuilder builder) {
    return builder.MapWhen(x => x.Request.Path.StartsWithSegments("/sitemap.xml"), 
      x => x.UseMiddleware<SitemapMiddleware>(route));
  } 
}

But the middleware uses an ISitemapService which I need to register as:

services.AddScoped<ISitemapService, SitemapService>();

How can I do this inside the method UseSitemap?

Or maybe create an IServicesCollection extension to use in Startup's ConfigureServices that registers the SitemapService?

Miguel Moura
  • 36,732
  • 85
  • 259
  • 481
  • AFAIK, the moment we are talking of Middleware, we are essentially talking within the context of a specific request. We can keep adding services to our service collection as long as the ServiceProvider is not built. But the time we hit our middleware pipeline, we already have it built and we cannot register services anymore. Why is it you want to delay the registration of your dependency in this case? – Sai Gummaluri Aug 08 '20 at 18:53
  • 1
    `Or maybe create an IServicesCollection extension to use in Startup's ConfigureServices that registers the SitemapService?` YES, that is usually the recommended approach. By the time `Startup.Configure` is invoked, the service provider is already built and cannot be modified. – Nkosi Aug 08 '20 at 19:04
  • @Nikosi So I suppose I should have UseSitemap extension method in Configure to add the Sitemap middleware and AddSitemap extension in ConfigureServices to add the Sitemap service and other Sitemap configurations ... Does this make sense? I am just trying to create a Sitemap component to be used in different projects but that follows the guidelines of ASP.NET Core for registering and configuring the Middleware – Miguel Moura Aug 10 '20 at 09:33
  • @SaiGummaluri I have no need to delay the registration ... Maybe using UseSitemap extension method in Configure to add the Sitemap middleware and AddSitemap extension in ConfigureServices to add the Sitemap service and other Sitemap configurations ... Does this make sense? I am just trying to create a Sitemap component to be used in different projects but that follows the guidelines of ASP.NET Core for registering and configuring the Middleware – Miguel Moura Aug 10 '20 at 09:34
  • Hi. Just a friendly reminder. Still no accepted answer for this question. Do you need something else? – Roar S. Aug 16 '20 at 18:55

0 Answers0