一个针对 Net Core 的非常具体的问题。我想为 IServiceCollection
编写一个扩展方法,它将在应用程序中进行配置。
原因是,如果目前而言,某些组件(例如属性和 Controller )位于单独的库中。因此,我想编写一个扩展方法,它将负责每个库的配置。 配置必须独立于主应用程序配置。
这是当前的代码(由于上述原因,我不喜欢它):
public void ConfigureServices(IServiceCollection services)
{
//..
services.AddMvc(options => {
// is needed for the library "filters".
options.Filters.Add(typeof(ExternalValidationActionFilterAttribute));
})
// is needed for the library "controllers"
.AddApplicationPart(typeof(ExternalController).Assembly)
.AddControllersAsServices();
//..
services.AddSingleton<ExternalControllerConfiguration>(new ExternalControllerConfiguration());
services.AddSingleton<ExternalValidationAttributeConfiguration>(new ExternalValidationAttributeConfiguration());
}
主应用程序的唯一方法是AddMvc()
。其余代码特定于外部库。我想避免将外部库特定逻辑与主应用程序逻辑混合。理想情况下,重构的代码应如下所示:
public void ConfigureServices(IServiceCollection services)
{
//..
services.AddMvc();
services.ConfigureExternalAttributes();
services.ConfigureExternalControllers();
//..
}
和
public static class ServiceCollectionExtensions
{
public static void ConfigureExternalAttributes(this IServiceCollection services)
{
// TBD: check if Mvc services added
// if not - add new, with options
// if yes - add options to existing
// options.Filters.Add(typeof(ExternalValidationActionFilterAttribute));
services.AddSingleton<ExternalValidationAttributeConfiguration>(new ExternalValidationAttributeConfiguration());
}
public static void ConfigureExternalControllers(this IServiceCollection services)
{
// TBD: check if Mvc services added
// if not - add new, with options
// if yes - add options to existing
// 1. If 'part' not present already: .AddApplicationPart(typeof(ExternalController).Assembly)
// 2. If 'AddControllersAsServices' not present already: .AddControllersAsServices();
// Else: skip
services.AddSingleton<ExternalControllerConfiguration>(new ExternalControllerConfiguration());
}
}
我的最后一个想法是去 git-hub,查看源代码并提出一些解决方案。但。有没有一些通用的方法可以达到这个结果?也许微软已经想到了这一点,所以我正在尝试重新实现轮子?
非常欢迎任何建议或代码示例。
最佳答案
对于应用程序部分,您可以使用 Microsoft.Extensions.DependencyInjection 包在单独的库中创建自定义扩展类,正如 Kirk Larkin 所建议的那样。
- 在单独的库中添加“Microsoft.Extensions.DependencyInjection”包。
Install-Package Microsoft.Extensions.DependencyInjection
- 在单独的库中创建一个新类ExternalConfigurationExtensions.cs,并按如下所述更新类命名空间。
namespace Microsoft.Extensions.DependencyInjection
{
public static class ExternalConfigurationExtensions
{
public static IMvcBuilder ConfigureExternalControllers(this IMvcBuilder builder)
{
if (builder == null)
throw new ArgumentNullException(nameof(builder));
builder.AddApplicationPart(typeof(ExternalController).Assembly);
return builder;
}
}
}
- 更新您的 Startup.cs
services.AddMvc()
.ConfigureExternalControllers();
关于c# - 添加Mvc服务后单独添加Mvc选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54862101/