1

I would like to wire in a DI container to an AWS lambda function. It would be nice if there were a base class architecture to facilitate SOLID principles in AWS Lambda. Obviously there is no startup.cs class or other .NET Core initialization facilities available.

This approach would allow one to service out the testable pieces of a larger lambda function.

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 Answer 1

4

I've been doing this with AutoFac and on every function call creates a new scope:

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);
        }
    }
}

The public static Lazy<ILifetimeScope> is also so I can mock it out in my tests.

[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);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.