简体   繁体   中英

What is correct way get an Object Instance in ConfigureServices itself?

With-in ConfigureServices method, what is right way of retrieving object instance?

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

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

EDIT: Why?: Microsoft doesn't recommend us to use this. https://docs.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-5.0#ASP0000

If you need a service to register another, you can use a different overload to register it, where you have access to IServiceProvider :

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

If you need a service to configure something, you can implement an IConfigureOptions<MyOptions> .

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

I use this in my project:

var authService = serviceProvider.GetService<SERVICES.Core.IAuthService>();

The difference between GetRequiredService<T> and GetService<T> Is that GetRequiredService<T> throws an exception if no service is found for the type T . While the GetService<T> returns null.

If you are ok to such a deal breaker use the first one, if you want to verify then you can use the second and check for null case. Depends on your case, I prefer the later in order to verify, though in most cases you would get a NullReferenceException .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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