如何使用.Net Core配置带有AWS Lambda函数的DI容器

问题描述 投票:0回答:1

我想将DI容器连接到AWS lambda函数。如果有一个基类架构来促进AWS Lambda中的SOLID原则,那就太好了。显然,没有startup.cs类或其他.net核心初始化工具可用。

这种方法可以让人们服务出更大的lambda函数的可测试部分。

任何有关这方面的想法将不胜感激。

public class Function : Startup
{
    private IFooService _fooService;

    public Function(IFooService fooService)
    {
        _fooService = fooService;   
    }

    public SkillResponse FunctionHandler(SkillRequest input, ILambdaContext context)
    {
       FooBar fooBar = _fooService.GetFooBar();
    }
}
c# .net amazon-web-services aws-lambda core
1个回答
3
投票

我一直在使用AutoFac进行此操作,并且在每个函数调用中创建一个新范围:

public class Functions
{
    public static Lazy<ILifetimeScope> LifetimeScope { get; set; } = new Lazy<ILifetimeScope>(CreateContainer);

    private static ILifetimeScope CreateContainer()
    {
        var containerBuilder = new ContainerBuilder();
        containerBuilder.RegisterType<ServerAbc>()
            .AsImplementedInterfaces();

        return containerBuilder.Build();
    }

    /// <summary>
    /// A Lambda function
    /// </summary>
    public async Task Handle(ILambdaContext context)
    {
        using (var innerScope = LifetimeScope.Value.BeginLifetimeScope())
        {
            var service = innerScope.Resolve<IServerAbc>();

            await service.GoDoWork()
                .ConfigureAwait(false);
        }
    }
}

public static Lazy<ILifetimeScope>也是如此,我可以在我的测试中嘲笑它。

[Fact]
public async Task ShouldMostLikelyWork()
{
    var lifetimeScope = new Mock<ILifetimeScope>();
    lifetimeScope.Setup(x => x.Resolve<IServerAbc>()).Returns(new MockService());

    Functions.LifetimeScope = new Lazy<ILifetimeScope>(() => lifetimeScope.Object);
    var functions = new Functions();

    await functions.Handle(Mock.Of<ILambdaContext>())
        .ConfigureAwait(false);
}
© www.soinside.com 2019 - 2024. All rights reserved.