我想将 DI 容器连接到 AWS lambda 函数。如果有一个基类架构来促进 AWS Lambda 中的 SOLID 原则,那就太好了。显然,没有可用的启动.cs类或其他 .NET Core 初始化工具。
这种方法将允许人们为更大的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();
}
}
我一直在用 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);
}