gpt4 book ai didi

c# - 在抽象基类中使用 Azure Functions?

转载 作者:行者123 更新时间:2023-12-02 06:12:26 24 4
gpt4 key购买 nike

我有一个正在运行的 FunctionApp,它公开了一些实体,它们都具有遵循相同模式的相同 CRUD 操作,我想知道是否有一种方法可以在代码中概括这一点。但我有点挣扎,因为所有内容都是使用属性声明的,并且它们需要引用常量,而这些常量不能在派生类中重写。

我理想地希望有一个这样的基类,但是我面临着常量的问题。

public abstract class EntityFunctions<T>
{
protected const string someConstant = "Derived?";
protected const string someOtherConstant = "Derived?";
protected readonly ICrudService<T> _crudService;

public EntityFunctions(ICrudService<T> crudService){
_crudService = crudService;
}

[FunctionName("Create" + someConstant)]
public async Task<string> Create([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = someOtherConstant)] T request)
{
return _crudService.Create(request);
}
}

public class MyEntityFunctions : EntityFunctions<MyEntity>{
...
}

有办法解决这个问题吗?确保唯一的函数名称和定义“基本”路由的其他方法。或者可以用其他方式注册函数吗?

最佳答案

虽然 FunctionMonkey 看起来是一个有趣的项目,但它对于我当前的项目来说有点太多了。相反,我设法使用 T4 模板来生成一些代码,因为我的需求非常简单。示例:

<#@ template debug="false" hostspecific="false" language="C#" #>
<#@ assembly name="System.Core" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ output extension=".Generated.cs" #>
namespace Mynamespace
{
<#
var entities = new List<(string, string)>() {
("MyEntity1", "my-entity1"),
("MyEntity1", "my-entity1")
};

foreach (var (entityType, path) in entities)
{
#>
#region <#= entityType #>
public class Base<#= entityType #>Functions
{
protected readonly ICrudService<<#= entityType #>> _crudService;

public Base<#= entityType #>Functions(ICrudService<<#= entityType #>> crudService)
{
_crudService = crudService;
}

[FunctionName("Get<#= entityType #>")]
public async Task<<#= entityType #>> Get([HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "<#= path #>/{ik}")] HttpRequest req, string id)
{
return await _crudService.Get(id);
}
}
#endregion
<#
}
#>
}

关于c# - 在抽象基类中使用 Azure Functions?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73034080/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com