0

I try to apply DI into Azure Function by reading this blog. The injected service in Azure Function belongs to another project which uses Structuremap for DI. My problem is that I can not add Structuremap registries into Azure Function Startup. Here is an example of Startup class

 public class Startup : FunctionsStartup
{
    public override void Configure(IFunctionsHostBuilder builder)
    {
        builder.Services.Configure();
    }
}

and I tried to write a ContainerConfigurator class (to add those registries)

public static class ContainerConfigurator
{
    public static void Configure(this IServiceCollection services)
    {
        var container = new Container(config =>
        {
            config.Scan(s =>
            {
                s.LookForRegistries();
                s.WithDefaultConventions();
                s.TheCallingAssembly();
            });
            config.Populate(services);
        });

        return container;
    }
}

and here is the Function class

public class FunctionX
{
    private readonly IXService _xService;

    public GetReports(IXService xService)
    {
        _xService = xService;
    }

    [FunctionName("GetX")]
    public async Task<IActionResult> Run(
        [HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequest req, ILogger log)
    {
        log.LogInformation("Get x");

        return await Task.FromResult(new OkObjectResult("OK"));
    }
}

when I test the endpoint, I get an error about the issue to resolve the "IXService". I do not know exactly what I miss. Does anyone have any solution?

ShrnPrmshr
  • 353
  • 2
  • 5
  • 17

1 Answers1

0

I think you need to explicitly register your service in startups:

public class Startup : FunctionsStartup
{
    public override void Configure(IFunctionsHostBuilder builder)
    {
        builder.Services.AddScoped<IXService, XService>();
    }
}

Even DI is supported in Azure function, but apparently it is little different from ASP.NET Core.

Jack Jia
  • 5,268
  • 1
  • 12
  • 14
  • thanks for this answer, I have tried this approach, but I was more wondering about this package structuremap.microsoft.dependencyinjection. what is the purpose of it in such cases? – ShrnPrmshr Oct 31 '19 at 07:24