.NET Core API网关(AWS)如何设置依赖项注入(DI)以使用MemCached.NET Core包、基于DI



我有一个基于.NET Core API网关的项目。我想引入依赖注入(di(,因为我需要引入的许多包都是基于这种模式的,所以需要使用IServiceCollection等等

我可以在网上找到将DI引入AWS Lambda的例子,这些例子只关注标准Lambda项目,其中的入口点是Handler函数。我不确定如何在我的API网关项目中复制这一点,因为它使用不同的结构。我有一个的无参数构造函数

Public Functions()
{}

以及的许多实例

public async Task<APIGatewayProxyResponse> MyProxyResponse(APIGatewayProxyRequest request, ILambdaContext context)
{
}

我不清楚如何将DI引入这个项目。例如,以.NET Core MemCached包为例,这里详细介绍了它https://github.com/cnblogs/EnyimMemcachedCore

我可以设置以下内容:

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

相关内容

  • 没有找到相关文章

最新更新