How to add LinkGenerator to ASP.NET Core?

Viewed 1621

How do I add a LinkGenerator object to my IServiceCollection for DI in the Startup.cs ConfigureServices method?

public MyService(LinkGenerator linkGenerator) { }

Have tried:

public static void AddLinkGenerator(this IServiceCollection services)
{
    services.AddHttpContextAccessor();
    services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();
    services.AddScoped<IUrlHelper, UrlHelper>(implementationFactory =>
    {
        var actionContext = implementationFactory.GetService<IActionContextAccessor>().ActionContext;
        return new UrlHelper(actionContext);
    });
}
1 Answers

As far as I know, the LinkGenerator servides will be registered when you call the services.AddRouting(); methods and this codes will be called when you run .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); in the program.cs methods.

So if you use configure the asp.net core application as a web host, there is no need to call services.AddRouting(); methods again in your ConfigureServices method. This service will be registered before startup.cs's ConfigureServices method.

You could refer to below source codes to know how it has been registerd in RoutingServiceCollectionExtensions class.

Notice: Since the DefaultLinkGenerator is internal class, we couldn't use services.TryAddSingleton<LinkGenerator, DefaultLinkGenerator>(); to just register the LinkGenerator class.

public static IServiceCollection AddRouting(this IServiceCollection services)
    {
          //....
         // Link generation related services
        services.TryAddSingleton<LinkGenerator, DefaultLinkGenerator>();
        services.TryAddSingleton<IEndpointAddressScheme<string>, EndpointNameAddressScheme>();
        services.TryAddSingleton<IEndpointAddressScheme<RouteValuesAddress>, RouteValuesAddressScheme>();
        services.TryAddSingleton<LinkParser, DefaultLinkParser>();

          //....
     }
Related