c# - 在 ConfigureServices() 中添加 AddMvc() 服务两次是 Asp.Net Core 中的一个好习惯吗?

标签 c# service asp.net-core-mvc nuget configure

我正在为 Asp.Net Core 创建一个 Nuget 包。我想让配置变得简单。因此,我决定提供一种流畅的方法,将我的 Nuget 添加到 Asp.Net Core 中 ConfigureServices() 的服务集合中。

这是我打算做的:

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

    services.AddMyNugetPackageName();
}

在我的 AddMyNugetPackageName() 方法中,

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;
}

现在如果人们开始使用我的 Nuget 包,我的 AddMyNugetPackageName() 中的 AddMvc() 是否会替换 AddMvc()他们的ConfigureServices()?会不会给终端用户带来麻烦?

如果这将替换用户在他们的 ConfigureServices() 中的 AddMvc() 那么什么是最好的方法或如何处理这个问题?

最佳答案

您可以使用 IConfigureOptions 模式从您的 nuget 包中注入(inject)一个 MvcOptions 配置

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

使用ConfigureOptions 注册您的选项

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

将您的 nuget 服务添加到服务集合

services.AddMvc();
services.AddMyNugetPackageName();

关于c# - 在 ConfigureServices() 中添加 AddMvc() 服务两次是 Asp.Net Core 中的一个好习惯吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55990151/

相关文章:

asp.net-core - ASP.NET Core 空项目。如何让 bower 和 wwwroot 正常工作

java - Spring中具有动态参数值的 Autowiring 类

mysql - 如何在数据库中创建Service Builder的表?

asp.net-mvc - MVC 6 网络农场 : The antiforgery token could not be decrypted

c# - Web 服务 - 方法命名?

c# - 运行程序集的 .NET 调度程序?

c# - 找不到不同程序集中的 ASP.NET Core ViewComponents

c# - SQLite 不能很好地运行 c#

c# - 字符串后的正则表达式行

c# - 如何将 "0"和 "1"转换为false和true