如何将 LinkGenerator 添加到 ASP.NET Core?

Ben*_*min 4 c# dependency-injection asp.net-core

如何在 Startup.cs方法中将LinkGenerator对象添加到我的for DI ?IServiceCollectionConfigureServices

public MyService(LinkGenerator linkGenerator) { }
Run Code Online (Sandbox Code Playgroud)

试过:

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);
    });
}
Run Code Online (Sandbox Code Playgroud)

Bra*_*ang 5

据我所知,当您调用这些方法时,将注册 LinkGenerator 服务,并且当您在 program.cs 方法中services.AddRouting();运行时,将调用此代码。 .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); });

因此,如果您使用将 ASP.NET Core 应用程序配置为 Web 主机,则无需 services.AddRouting();在ConfigureServices 方法中再次调用方法。该服务将在startup.cs的ConfigureServices方法之前注册。

您可以参考下面的源代码来了解它是如何注册到 RoutingServiceCollectionExtensions 类中的。

注意:由于DefaultLinkGenerator是内部类,我们不能 services.TryAddSingleton<LinkGenerator, DefaultLinkGenerator>();只注册LinkGenerator类。

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>();

          //....
     }
Run Code Online (Sandbox Code Playgroud)