I try to resolve a handler by this suggested solution with the help of StructureMap.Microsoft.DependencyInjection
I have an Azure Function, QueueTrigger which gets a message and tries to find the right handler for the message. For this function, I use DI and here is the Startup class
[assembly: FunctionsStartup(typeof(Api.Startup))]
namespace Api
{
public class Startup : FunctionsStartup
{
public override void Configure(IFunctionsHostBuilder builder)
{
builder.Services.ConfigureIoc();
}
}
}
ConfigureIoC class is like this
public static class Configuration
{
public static IServiceProvider ConfigureIoc(this IServiceCollection services)
{
services.AddService();
services.AddCosmosDb();
IContainer container = new Container();
container.Configure(configure: config =>
{
config.For<IHandler>().Add<xHandler>().Named("handlerName");
config.Populate(services);
});
return container.GetInstance<IServiceProvider>();
}
}
The function is like this
public class NameOfFunction
{
private readonly IxProcessor _xProcessor;
public NameOfFunction(IxProcessor xProcessor)
{
_xProcessor = xProcessor;
}
[FunctionName("FunctionName")]
public async void Run([QueueTrigger("x-queue", Connection = "AzureWebJobsStorage")]string myQueueItem, ILogger log)
{
log.LogInformation($"Starting to process scheduled report job: {myQueueItem}");
try
{
await _xProcessor.Process(myQueueItem);
}
catch (Exception ex)
{
log.LogError($"Exception while processing job queue event: {myQueueItem}. Exception: {ex}");
throw;
}
}
}
The place I need to use those registered for IHandler is used in IxProcessor which is
public sealed class xProcessor : IxProcessor
{
private readonly IContainer _container;
public xProcessor(IContainer container)
{
_container = container;
}
public async Task Process(string xMessage)
{
var jObject = JsonConvert.DeserializeObject<JObject>(xMessage);
var xName = jObject["Name"].ToString();
var handler = _container.GetInstance<IHandler>(xName);
await handler.Handle(xMessage);
}
}
But it seems the container is null. (IContainer belongs to StructureMap)
public xProcessor(IContainer container)
{
_container = container;
}
I do not know exactly what do I miss during this configuration. Does anyone have any idea/hint?