ASP.NET Core Interview Question #65
How can you register a service using a factory delegate?
Dependency Injection & Services Junior Beginner
Quick Interview Answer
A factory delegate allows custom logic to run when the DI container creates a service. The delegate receives an IServiceProvider, so it can resolve other registered services and configuration needed to construct the object.
Detailed Explanation
A factory delegate allows custom logic to run when the DI container creates a service. The delegate receives an IServiceProvider, so it can resolve other registered services and configuration needed to construct the object.
Factory registrations are useful when construction requires values that cannot be expressed through ordinary constructor activation or when an external type requires manual setup.
The factory should remain focused on object construction. Complex business selection logic is usually better placed in a dedicated application service.
Code Example
builder.Services.AddSingleton<IMyClient>(sp =>
{
var configuration = sp.GetRequiredService<IConfiguration>();
var baseUrl = configuration["MyApi:BaseUrl"]
?? throw new InvalidOperationException("MyApi:BaseUrl is missing.");
return new MyClient(baseUrl);
});