Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is adding AddMvc() Service twice in ConfigureServices() a good practice in Asp.Net Core?

I'm creating a Nuget Package for Asp.Net Core. I want to make it simple to configure. So I decided to give a fluent way approach to add my Nuget to the service collection in ConfigureServices() in Asp.Net Core.

This is what I'm planning to do:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc(options => options....);

    services.AddMyNugetPackageName();
}

Inside my AddMyNugetPackageName() method,

public static IServiceCollection AddMyNugetPackageName(this IServiceCollection services)
{
    services
        .AddMvc(options => options.ModelBinderProviders.Insert(0, new MyModelBinderProvider()))
        .AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());

    return services;
}

So now if people start using my Nuget package, will the AddMvc() inside my AddMyNugetPackageName() replace the AddMvc() in their ConfigureServices()? Will this cause any trouble to the end users?

If this will replace the user's AddMvc() in their ConfigureServices() then what is the best approach or how to handle this?

like image 876
fingers10 Avatar asked May 05 '19 08:05

fingers10


1 Answers

You can use the IConfigureOptions pattern to inject a MvcOptions configuration from your nuget package

public class MyConfigureOptions : IConfigureOptions<MvcOptions>
{
    public void Configure(MvcOptions options)
    {
        options.ModelBinderProviders.Insert(0,new MyModelBinderProvider());
    }
}

Use ConfigureOptions to register your options

public static IServiceCollection AddMyNugetPackageName(this IServiceCollection services)
{
    services.ConfigureOptions<MyConfigureOptions>();
}

Add your nuget services to the service collection

services.AddMvc();
services.AddMyNugetPackageName();
like image 198
James Sampica Avatar answered Sep 18 '22 15:09

James Sampica