![](/img/trans.png)
[英]How do I inject an instance of an objct into the “create” function of .NET Core DI Container
[英]How Would I Configure a DI container with a AWS Lambda Function using .NET Core?
我想将 DI 容器连接到 AWS lambda 函数。 如果有一个基类架构来促进 AWS Lambda 中的 SOLID 原则,那就太好了。 显然,没有可用的 startup.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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.