I would like to register in- and outputformatters in DI, however I don't know how to get to the DI container in the AddControllers
method:
var builder = WebApplication.CreateBuilder(args);
builder.Services
.AddTransient<TexInputFormatter, MyInputFormatter>()
.AddTransient<TextOutputFormatter, MyOutputFormatter>()
.AddControllers(c =>
{
c.InputFormatters.Clear();
c.OutputFormatters.Clear();
// How do I get to the DI container here?
c.InputFormatters.Add(???.GetRequiredService<TextInputFormatter>());
c.OutputFormatters.Add(???.GetRequiredService<TextOutputFormatter>());
});
var app = builder.Build();
app.Run();
I did come up with one 'workaround' by declaring app
earlier and the capturing it, but I don't like that solution:
WebApplication? app = null; // Declare app here
var builder = WebApplication.CreateBuilder(args);
builder.Services
.AddTransient<TexInputFormatter, MyInputFormatter>()
.AddTransient<TextOutputFormatter, MyOutputFormatter>()
.AddControllers(c =>
{
c.InputFormatters.Clear();
c.OutputFormatters.Clear();
// Use app.Services here
c.InputFormatters.Add(app!.Services.GetRequiredService<TextInputFormatter>());
c.OutputFormatters.Add(app!.Services.GetRequiredService<TextOutputFormatter>());
});
app = builder.Build();
app.Run();
Edit: Ofcourse I could do:
c.InputFormatters.Add(new MyInputFormatter());
c.OutputFormatters.Add(new MyOutputFormatter());
However, both formatters have a bunch of other dependencies and constructor arguments I want DI to resolve for me.
How would I go about this?