【问题标题】:DI in Azure Function using Simple InjectorAzure Function 中的 DI 使用 Simple Injector
【发布时间】:2020-05-12 13:28:54
【问题描述】:

我想使用 Simple Injector 在 Azure Fuctions 中注入命令处理程序、ILogger 和 TelemetryClient。

这是我的 Azure 函数:

[FunctionName("ReceiveEvent")]
public static async Task<IActionResult> Run(
    [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req,
    ILogger log,
    ICommandMapper commandMapper,
    ICommandValidator commandValidator,
    ICommandHandlerService commandHandlerService)
{
    log.LogInformation("ReceiveEvent HTTP trigger function started processing request.");

    IActionResult actionResult = null;

    string requestBody = await new StreamReader(req.Body).ReadToEndAsync();

    var command = await commandMapper.Map(requestBody);

    if (commandValidator.Validate(req, command, ref actionResult))
    {
        //TODO
        commandHandlerService.HandleCommand(command);
        return actionResult;
    }

    return actionResult;
}

这是我的引导程序类:

public class Bootstrapper
{
    public static void Bootstrap(IEnumerable<Assembly> assemblies = null, bool verifyContainer = true)
    {
        Container container = new Container();

        container.Register(typeof(ICosmosDBRepository<>), typeof(CosmosDBRepository<>).Assembly);
        container.Register(typeof(IAzureBlobStorage), typeof(AzureBlobStorage).Assembly);
        container.Register(typeof(ICommandMapper), typeof(CommandMapper).Assembly);
        container.Register(typeof(ICommandValidator), typeof(CommandValidator).Assembly);
        container.Register(typeof(ICommandHandlerService), typeof(CommandHandlerService).Assembly);

        List<Assembly> myContextAssemlies = new List<Assembly>
            {
                 Assembly.GetAssembly(typeof(CardBlockCommandHandler)),
            };

        container.Register(typeof(ICommandHandler), myContextAssemlies, Lifestyle.Scoped);

        assemblies = assemblies == null
            ? myContextAssemlies
            : assemblies.Union(myContextAssemlies);

        if (verifyContainer)
        {
            container.Verify();
        }
    }
}

现在我的问题是,我将如何在 Azure Function 中使用此引导程序方法解决 DI?

我需要在 FunctionsStartup 中注册引导方法吗?

【问题讨论】:

  • @Steven 我更新了我的问题。你能建议吗
  • @Steven 我已经更新了我的问题,请您现在提出建议
  • @Steven 我已经更新了我的天蓝色函数,

标签: c# dependency-injection azure-functions simple-injector


【解决方案1】:

使用 Simple Injector,您无需将服务注入 Azure Function。这是不支持的。相反,integration guide 解释说:

不是将服务注入 Azure Function,而是将所有业务逻辑从 Azure Function 移出到应用程序组件中。函数的依赖可以成为组件构造函数的参数。可以从 Azure 函数中解析和调用此组件。

对于您的特定情况,这意味着执行以下步骤:

1。将所有业务逻辑从 Azure Function 移出到应用程序组件中。函数的依赖可以成为组件构造函数的参数。

public sealed class ReceiveEventFunction
{
    private readonly ILogger log;
    private readonly ICommandMapper commandMapper;
    private readonly ICommandValidator commandValidator;
    private readonly ICommandHandlerService commandHandlerService;

    public ReceiveEventFunction(ILogger log, ICommandMapper commandMapper,
        ICommandValidator commandValidator, ICommandHandlerService commandHandlerService)
    {
        this.log = log;
        this.commandMapper = commandMapper;
        this.commandValidator = commandValidator;
        this.commandHandlerService = commandHandlerService;
    }
    
    public async Task<IActionResult> Run(HttpRequest req)
    {
        IActionResult actionResult = null;

        string requestBody = await new StreamReader(req.Body).ReadToEndAsync();

        var command = await commandMapper.Map(requestBody);

        if (commandValidator.Validate(req, command, ref actionResult))
        {
            commandHandlerService.HandleCommand(command);
            return actionResult;
        }

        return actionResult;    
    }
}

2 该组件可以在 Azure 函数中解析和调用。

[FunctionName("ReceiveEvent")]
public static async Task<IActionResult> Run(
    [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req)
{
    // Resolve the service
    var service = Bootstrapper.Container.GetInstance<ReceiveEventFunction>();
    
    // Invoke the service
    service.Run(req);
}

3。最后的步骤

要完成配置,您必须确保(新)静态 Bootstrapper.Container 字段存在,并且 ReceiveEventFunction 已注册:

public class Bootstrapper
{
    public static readonly Container Container;

    static Bootstrapper()
    {
        Container = new Bootstrapper().Bootstrap();
    }

    public static void Bootstrap(
        IEnumerable<Assembly> assemblies = null, bool verifyContainer = true)
    {
        Container container = new Container();

        container.Register<ReceiveEventFunction>();

        ... // rest of your configuration here.
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多