问题
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?
回答1:
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/
来源:https://stackoverflow.com/questions/56653105/cant-figure-out-how-to-inject-linkgenerator