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

时间:2018-04-17 18:15:10

标签: c# .net amazon-web-services aws-lambda core

我想将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();
    }
}

1 个答案:

答案 0 :(得分: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);
}