I am referring to this link that explains how to implement DI in Azure functions. I want to implement a Factory
pattern where my Factory class
should be able to resolve other dependencies while constructing the factory object.
Here is the code.
public class Startup : FunctionsStartup
{
public override void Configure(IFunctionsHostBuilder builder)
{
System.Console.WriteLine("***************************I am in startup....");
builder.Services.AddScoped<PayloadProcessorFactory>();
/* I tried to explicitly add IFunctionsHostBuilder to Services but its not working.
builder.Services.AddScoped<IFunctionsHostBuilder>((s) =>{
System.Console.WriteLine("test");
return builder;
});*/
/*No problem with below two dependencies and are getting injected without any issue*/
builder.Services
.AddScoped<IPayloadProcessor,DoctorPayloadProcessor>()
.AddScoped<DoctorPayloadProcessor>();
builder.Services
.AddScoped<IPayloadProcessor,PatientPayloadProcessor>()
.AddScoped<PatientPayloadProcessor>();
}
}
Here is my factory class
public class PayloadProcessorFactory
{
private readonly IFunctionsHostBuilder builder;
private readonly ILogger _logger;
public PayloadProcessorFactory(IFunctionsHostBuilder builder,ILogger<PayloadProcessorFactory> logger)
{
_logger = logger;
this.builder = builder; //Builder is always null
_logger.LogDebug("Constructing PayloadProcesorFactory");
}
}
In the above code value of builder is always null hence I can't resolve dependencies using following statement
payloadProcessor = builder.Services.BuildServiceProvider()
.GetRequiredService<DoctorPayloadProcessor>();
In Startup.cs
I tried to explicitly add IFunctionsHostBuilder
to the service collection
but after that, I ran into below issue.
Exception has occurred: CLR/System.InvalidOperationException
An exception of type 'System.InvalidOperationException' occurred in Microsoft.Extensions.DependencyInjection.dll but was not handled in user code: 'Unable to resolve service for type 'Microsoft.Azure.WebJobs.Script.IEnvironment' while attempting to activate 'Microsoft.Azure.WebJobs.Script.Configuration.ScriptHostOptionsSetup'.'
QUESTION
How can I inject IServiceProvider
to my factory class in order to build a complex objects and resolve multiple dependencies?
Project details
- Dotnet framework - netcoreapp2.1
- Azure functions version : 2.0