Can't figure out how to inject LinkGenerator

Viewed 1096

So I know how to setup my controller so that I can accept a LinkGenerator injected into the controller. What I can't figure out is how do I inject my controller at startup with a LinkGenerator.

Controller

protected readonly LinkGenerator _linkGenerator;

public SomeController(config config, LinkGenerator linkGenerator)
{
        config = Config;
        _linkGenerator = linkGenerator;
}

StartUp - ConfigureServices

Controllers.SomeController someController = new 
Controllers.SomeController(config, linkGenerator); //how do I get an 
instance of link generator here.

services.AddSingleton(someController);

I tried this in the Configure method of startup, but ConfigureServices runs before Configure

app.Use(async (context, next) =>
{
     linkGenerator = context.RequestServices.GetService<LinkGenerator>();
});

What am I missing?

2 Answers

Try the following approach in ConfigureServices of Startup.cs

public Startup(IConfiguration configuration , IHttpContextAccessor accessor)
{
    Configuration = configuration;
    _accessor = accessor;
}

public readonly IHttpContextAccessor _accessor;
public IConfiguration Configuration { get; }

var linkGenerator = _accessor.HttpContext.RequestServices.GetService<LinkGenerator>();
services.AddScoped<LinkGenerator>();
services.AddTransient(ctx =>
            new ValuesController(linkGenerator));

Controller

private readonly LinkGenerator _linkGenerator;

public ValuesController(LinkGenerator linkGenerator)
{
     _linkGenerator = linkGenerator;
}

Reference :https://andrewlock.net/controller-activation-and-dependency-injection-in-asp-net-core-mvc/

I found this article: https://kontext.tech/article/974/generate-absolute-path-using-linkgenerator-in-aspnet-core. It states:

To use this class in your code, we need to inject it. LinkGenerator is a singleton service available from DI. It is registered automatically when you call services.AddRouting();. All the methods also need to access HttpContext instance for each request, which can be accessed by injecting HttpContextAccessor.

services.AddHttpContextAccessor();

Related