Austin Shaw
Austin Shaw

Reputation: 334

How to configure service options after it has been added to the collection?

Is there a way to configure options for a service (in this case AddMvc) after it has been added to the services collection? Here is an example of what I need:

Add service like normal:

services.AddMvc(opt =>
{
    ...
});

Then, later on in the code, update\add some options on the service that has already been added.

services.AddMvc().AddJsonOptions(opt =>
{
    ...
});

This is an API pipeline, built using .NET Core 2.2.

Upvotes: 1

Views: 755

Answers (1)

Kirk Larkin
Kirk Larkin

Reputation: 93053

The call to AddJsonOptions adds a configuration delegate, which is invoked later in time when an instance of MvcJsonOptions is actually built/configured. You can achieve the same result later on by adding a call to Configure<T> on the IServiceCollection itself:

services.AddMvc(opt =>
{
    // ...
});

// ...

services.Configure<MvcJsonOptions>(opt =>
{
    // ...
});

Reference: Configure simple options with a delegate.

Upvotes: 2

Related Questions