简体   繁体   English

.net 核心 Startup.cs CreateScope 或 BuildServiceProvider

[英].net core Startup.cs CreateScope or BuildServiceProvider

I am just creating a new API and I have noticed from a couple of projects that I try to get Config files inside Startup.cs in different ways.我只是在创建一个新的 API,我从几个项目中注意到我尝试以不同的方式在 Startup.cs 中获取配置文件。 The first way is like this:第一种方式是这样的:

var serviceProvider = services.BuildServiceProvider();
var config = serviceProvider.GetRequiredService<IIdentityServerConfig>();

and the second way is like this:第二种方式是这样的:

var scope = services.BuildServiceProvider().CreateScope();
var config = scope.ServiceProvider.GetRequiredService<Auth0Config>();

My question is, which one is right?我的问题是,哪一个是对的? Or does it not matter?还是没关系?


Here is an example:这是一个例子:

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(m => m.AddPolicy(CorsName, o => o.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod()));
    services.AddLogging(Configuration, nameof(DataConfig));

    AddConfigs(services);
    AddSingletons(services);
    AddTransients(services);

    ConfigureStripe(services);

    AddDatabaseContexts(services);
    AddAuthentication(services);
    AddServices(services);

    services.AddMvc().AddFluentValidation(m => m.RegisterValidatorsFromAssemblyContaining<QuestionValidator>());
}

The AddConfigs method looks like this: AddConfigs方法如下所示:

private void AddConfigs(IServiceCollection services)
{
    services.Configure<Auth0Config>(Configuration.GetSection(nameof(Auth0Config)));
    services.Configure<DataConfig>(Configuration.GetSection(nameof(DataConfig)));
    services.Configure<EvaluatorConfig>(Configuration.GetSection(nameof(EvaluatorConfig)));
    services.Configure<StripeConfig>(Configuration.GetSection(nameof(StripeConfig)));
    services.Configure<CookiePolicyOptions>(options =>
    {
        // This lambda determines whether user consent for non-essential cookies is needed for a given request.
        options.CheckConsentNeeded = context => true;
        options.MinimumSameSitePolicy = SameSiteMode.None;
    });

    services.AddSingleton(m => m.GetRequiredService<IOptions<Auth0Config>>().Value);
    services.AddSingleton(m => m.GetRequiredService<IOptions<DataConfig>>().Value);
    services.AddSingleton(m => m.GetRequiredService<IOptions<EvaluatorConfig>>().Value);
    services.AddSingleton(m => m.GetRequiredService<IOptions<StripeConfig>>().Value);
}

And then you can see how I get a config for other services (for example the AddAuthentication method:然后你可以看到我如何获得其他服务的配置(例如AddAuthentication方法:

private static void AddAuthentication(IServiceCollection services)
{
    var scope = services.BuildServiceProvider().CreateScope();
    var config = scope.ServiceProvider.GetRequiredService<Auth0Config>();

    services.AddAuthentication(options =>
    {
        options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    }).AddJwtBearer("Bearer", options =>
    {
        options.Authority = config.Authority;
        options.Audience = config.ApiAudience;
    });
}

First, you need to add services to DI container.首先,您需要向 DI 容器添加服务。 The common approach is to do that in ConfigureServices from Startup (also it is possible in Program.cs)常见的方法是在StartupConfigureServices中执行此操作(在 Program.cs 中也可以)

You don't need to call services.BuildServiceProvider() if you need an instance of IIdentityServerConfig in ConfigureServices method because you should already have it.如果您需要ConfigureServices方法中的IIdentityServerConfig实例,则无需调用services.BuildServiceProvider() ,因为您应该已经拥有它。

If you need the instance of IIdentityServerConfig in Configure method, then just pass it as a parameter like:如果您在Configure方法中需要IIdentityServerConfig的实例,则只需将其作为参数传递,例如:

public void Configure(IApplicationBuilder app, IIdentityServerConfig config)
{
}

or use app :或使用app

app.ApplicationServices.GetService<IIdentityServerConfig>();

so, the right way is not building service provider in Startup file所以,正确的方法是不在启动文件中建立服务提供者

but if you really need this, I would prefer to use this one if you don't need a new scope (I think you don't need)但如果你真的需要这个,如果你不需要新的 scope,我更愿意使用这个(我认为你不需要)

var serviceProvider = services.BuildServiceProvider();
var config = serviceProvider.GetRequiredService<IIdentityServerConfig>();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM