如何解决.NET Core API网关AWS如何设置依赖注入DI以使用MemCached .NET Core程序包,基于DI的记录器等
我有一个基于.NET Core API Gateway的项目。我想介绍依赖注入(di),因为我需要介绍的许多软件包都基于这种模式,因此需要使用IServiceCollection等。
我可以在网上找到将DI引入AWS Lambda的示例仅集中于标准Lambda项目,其中入口点是Handler函数。我不确定如何使用我的API Gateway项目复制它,因为它使用不同的结构。我有一个无参数的
构造函数Public Functions()
{}
还有许多实例
public async Task<APIGatewayProxyResponse> MyProxyResponse(APIGatewayProxyRequest request,ILambdaContext context)
{
}
我不清楚如何将DI引入该项目。例如,以{.3}}
中详细介绍的.NET Core MemCached软件包为例。我可以设置以下内容:
public class Functions
{
public IConfiguration Configuration { get; private set; }
private void ConfigureServices(IServiceCollection serviceCollection)
{
serviceCollection.AddEnyimMemcached();
serviceCollection.AddEnyimMemcached(options => options.AddServer(Environment.GetEnvironmentVariable("CACHE_URL"),Convert.ToInt32(Environment.GetEnvironmentVariable("CACHE_PORT"))));
// TODO: Register services with DI system
}
private readonly AmazonSimpleSystemsManagementClient _systemsManagementClient;
private readonly JSchema _jSchema;
private readonly loyaltyContext _loyaltyContext;
private readonly IMemcachedClient _memcachedClientv2;
但是_memcachedClientv2从未分配给它,因此它的值将为null。我不确定如何从以上方法获取每个 APIGatewayProxyRequest 方法中有效的_memcachedClientv2。
解决方法
Naadem Taj已经为您指明了正确的方向,但这是一个需要澄清的示例。
您希望在Startup.cs中设置服务,然后可以访问在您创建的其他服务中的服务。
举个例子:
public class Startup
{
public IConfiguration Configuration { get; private set; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
private void ConfigureServices(IServiceCollection serviceCollection)
{
serviceCollection.AddEnyimMemcached(options =>
options.AddServer(Environment.GetEnvironmentVariable("CACHE_URL"),Convert.ToInt32(Environment.GetEnvironmentVariable("CACHE_PORT"))));
serviceCollection.AddScoped<IFunctions,Functions>();
// TODO: Register services with DI system
}
}
和您的功能中
public interface IFunctions
{
async Task DoStuff();
}
public class Functions : IFunctions
{
private readonly AmazonSimpleSystemsManagementClient _systemsManagementClient;
private readonly JSchema _jSchema;
private readonly loyaltyContext _loyaltyContext;
private readonly IMemcachedClient _memcachedClientv2;
public Functions(loyaltyContext context,AmazonSimpleSystemsManagementClient amazonClient,JSchema jschema,IMemcachedClient memcachedClient)
{
_loyaltyContext = context;
_systemsManagementClient= amazonClient;
_jSchema = jschema;
_memcachedClientv2 = memcachedClient;
}
public async Task DoStuff()
{
// Do stuff here
}
}