gpt4 book ai didi

asp.net - 从 ASP.NET Core 2.2 迁移到 3.1 时 services.BuildServiceProvider(在ConfigureServices 中)的替代代码

转载 作者:行者123 更新时间:2023-12-02 14:17:03 25 4
gpt4 key购买 nike

我有模块化的 ASP.NET Core 应用程序。回到 .NET Core 1.1 时代,我在 public void ConfigureServices(IServiceCollection services) 方法中构建服务(AddScopedAddSingleton ...)像这样:

public void ConfigureServices(IServiceCollection services)
{
//...
var sp = services.BuildServiceProvider();
GlobalConfiguration.ModuleInitializers = sp.GetServices<IModuleInitializer>();
foreach (var moduleInitializer in GlobalConfiguration.ModuleInitializers)
moduleInitializer.ConfigureServices(services, this.Configuration, this.Environment);
}

每个模块(库)都有自己的类,它实现“IModuleInitializer”并注册服务:

public class ModuleInitializer : IModuleInitializer
{
public void ConfigureServices(IServiceCollection serviceCollection, IConfiguration configuration, IHostingEnvironment environment)
{
serviceCollection.AddScoped<....>();
serviceCollection.AddScoped<...>();
...

从 .NET Core 2.2 迁移到 3.1 时,我收到警告:

Calling 'BuildServiceProvider' from application code results in an additional copy of singleton services being created. Consider alternatives such as dependency injecting services as parameters to 'Configure'

我已经了解了这意味着什么,问题出在哪里......,但是我在如何在模块设计应用程序中正确配置服务方面遇到了问题。

我还需要从互联网获取有关模块的信息。我的问题是这种方法是否好,或者有更好/推荐的吗?

public Startup(IConfiguration configuration)
{
Configuration = configuration; //From https://learn.microsoft.com/en-us/aspnet/core/fundamentals/startup?view=aspnetcore-3.1
}

public void ConfigureServices(IServiceCollection services)
{
...

var serverSett = this.Configuration.GetSection("Server").Get<ServerSettings>();
string[] allowedModules;
using (var httpClientHandler = new HttpClientHandler())
{
allowedModules = //Get allowed modules from web
}
if (allowedModules.Any(t => t == "Shopping");
services.AddShopping(); //Extension method in Shopping library which register own services.
if (allowedModules.Any(t => t == "Offer");
services.AddOffer(); //Extension method in Offer library which register own services.
}

最佳答案

使用 DI 来设置 DI 有点问题,而且肯定会出现问题。

为什么不直接使用一些反射来获取 IModuleInitializers。

var moduleInitializers = typeof(MyAssembly).GetTypeInfo().Assembly
.GetTypes()
.Where(type =>
!type.GetTypeInfo().IsAbstract &&
typeof(IModuleInitializer).IsAssignableFrom(type))
.Select(type => Activator.CreateInstance(type))
.Cast<IModuleInitializer>()
.ToArray();

foreach (var moduleInitializer in moduleInitializers)
moduleInitializer.ConfigureServices(services, this.Configuration, this.Environment);

关于你的第二个问题我无法给你建议。但我会质疑动态设置应用程序的必要性,除非您确实需要这样做。

关于asp.net - 从 ASP.NET Core 2.2 迁移到 3.1 时 services.BuildServiceProvider(在ConfigureServices 中)的替代代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59316820/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com