【问题标题】:What is correct way get an Object Instance in ConfigureServices itself?在 ConfigureServices 本身中获取对象实例的正确方法是什么?
【发布时间】:2021-10-03 10:32:38
【问题描述】:

ConfigureServices方法中,检索对象实例的正确方法是什么?

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddScoped<SERVICES.Core.IAuthService, SERVICES.Core.AuthService>();
        //.......

        var serviceProvider = services.BuildServiceProvider();
        var authService = serviceProvider.GetRequiredService<IAuthService>();
    }

编辑: 为什么?:Microsoft 不建议我们使用它。 https://docs.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-5.0#ASP0000

【问题讨论】:

  • serviceProvider.GetRequiredService&lt;SERVICES.Core.IAuthService&gt;();
  • var authService = serviceProvider.GetService&lt;SERVICES.Core.IAuthService&gt;(); 我在我的项目中使用它。
  • @vsarunov 和 @Chetan 是为 IServiceProvider 而不是 IServiceCollection
  • 你为什么需要它?它应该被注入到需要它的对象中
  • 你为什么要这样做呢?我以前做过并修复它以进行正确的注射

标签: c# .net-core


【解决方案1】:

如果您需要一个服务来注册另一个服务,您可以使用不同的重载来注册它,您可以访问IServiceProvider

services.AddScoped<IAnotherService>(
    provider =>
    {
        var authService = provider.GetRequiredService<IAuthService>();
        return new AnotherServiceImplementation(authService);
    }
);

如果你需要一个服务来配置一些东西,你可以实现一个IConfigureOptions&lt;MyOptions&gt;

services.AddSingleton<IConfigureOptions<MyOptions>, ConfigureMyOptions>();
class ConfigureMyOptions: IConfigureOptions<MyOptions>
{
    private IAuthService _authService; // inject a service
    private IConfiguration _configuration; // a configuration
    private SomeOptions _someOptions; // an option

    public ConfigureMyOptions(IAuthService authService, IConfiguration configuration, IOptions<SomeOptions> someOptions)
    {
        _authService = authService;
        _configuration = configuration;
        _someOptions = someOptions.Value;
    }

    public void Configure(MyOptions options)
    {
        // use _authService
        var something = _authService.GetSomething();
        _configuration.GetSection("MyOptions").Bind(options);
    }
}

【讨论】:

【解决方案2】:

我在我的项目中使用它:

var authService = serviceProvider.GetService&lt;SERVICES.Core.IAuthService&gt;();

GetRequiredService&lt;T&gt;GetService&lt;T&gt; 的区别 如果没有找到T 类型的服务,那GetRequiredService&lt;T&gt; 是否会抛出异常。而GetService&lt;T&gt; 返回 null。

如果您同意这样的交易破坏者,请使用第一个,如果您想验证,则可以使用第二个并检查 null 案例。取决于你的情况,我更喜欢后者来验证,但在大多数情况下你会得到一个NullReferenceException

【讨论】:

  • 那是 IServiceProvider 而不是 IServiceCollection。 OP 询问解决服务 inside ConfigureServices
  • @abdusco 看清楚OP提供的例子。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-04
相关资源
最近更新 更多