Reputation: 13856
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://learn.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-5.0#ASP0000
Upvotes: 0
Views: 607
Reputation: 11091
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);
}
}
Upvotes: 3
Reputation: 1547
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
.
Upvotes: 1