首页 > 解决方案 > 从 Azure 队列 Run() 方法内部调用实体框架核心工作单元?

问题描述

在我的队列中,我正在生成一个需要保存到数据库的报告。

我尝试像这样注入我的工作单元/存储库:

        [FunctionName("AppExecution")]
        public static void Run(
            [QueueTrigger("some-name", Connection = "ConnectionStrings")]
            string     myQueueItem,
            ILogger    log,
            UnitOfWork Work
            // IRepository<SomeClass> Repo  // <-- doesn't work either :(
        )
        { ... }

但它没有用。运行时出现此错误:

Microsoft.Azure.WebJobs.Host:索引方法“AppExecution”出错。Microsoft.Azure.WebJobs.Host:无法将参数“Work”绑定到类型 UnitOfWork。确保绑定支持参数类型。如果您正在使用绑定扩展(例如 Azure 存储、ServiceBus、计时器等),请确保您已在启动代码中调用了扩展的注册方法(例如 builder.AddAzureStorage()、builder.AddServiceBus( )、builder.AddTimers() 等)。

请问有什么建议吗?我真的需要将结果数据保存回数据库!

标签: c#entity-framework-coreasp.net-core-3.1

解决方案


您需要使类非静态和函数非静态,然后将您的对象注入到类构造函数中。在docs中有一些描述。例如:

public class AppExecutionFunction
{
    private readonly UnitOfWork _unitOfWork;

    public AppExecutionFunction(UnitOfWork unitOfWork)
    {
        _unitOfWork = unitOfWork;
    }

    [FunctionName("AppExecution")]
    public void Run(
        [QueueTrigger("some-name", Connection = "ConnectionStrings")]
        string     myQueueItem,
        ILogger    log)
    {
        _unitOfWork.CallMethod();
    }
}

推荐阅读