在 Azure Functions v2 上使用 MySqlDatabase (MySql.Data.MySqlClient) - "Unable to resolve service"

Using MySqlDatabase (MySql.Data.MySqlClient) on Azure Functions v2 - "Unable to resolve service"

我创建了一个使用 MySql.Data.MySqlClient 依赖项的 Azure Functions 应用 ~v2 项目。

该项目设置为还使用 SwashBuckle 库来创建可调用的 API。

当我从我的本地设置执行我的项目时,它工作正常。然而,当我将 Functions 应用程序发布到我们的 Azure 服务器并尝试在那里测试该功能时,我收到此错误:

System.InvalidOperationException : Unable to resolve service for type 'MyFunctionApp.MySqlDatabase' while attempting to activate 'MyFunctionApp.PostsService'.

at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp,Type type,Type requiredBy,Boolean isDefaultParameterRequired)

...

我的StartUp.cs:

using System;
using System.Reflection;
using AzureFunctions.Extensions.Swashbuckle;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Hosting;
using Microsoft.Extensions.DependencyInjection;
using MyFunctionApp;

[assembly: WebJobsStartup(typeof(SwashBuckleStartup))]
namespace MyFunctionApp
{
    internal class SwashBuckleStartup : IWebJobsStartup
    {
        public void Configure(IWebJobsBuilder builder)
        {
            ConfigureServices(builder.Services);
            builder.AddSwashBuckle(Assembly.GetExecutingAssembly());
        }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddScoped<MySqlDatabase>(_ => new MySqlDatabase(Environment.GetEnvironmentVariable("MyFunctionApp-DbConn")));
        }
    }
}

我的MySqlDatabase.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;

namespace MyFunctionApp
{
    public class MySqlDatabase : IDisposable
    {
        public MySqlConnection Connection;

        public MySqlDatabase(string connectionString)
        {
            Connection = new MySqlConnection(connectionString);
            this.Connection.Open();
        }

        public void Dispose()
        {
            Connection.Close();
        }
    }
}

这是我正在调用的服务,它抛出了上述错误 (PostsService.cs):

using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using System.Net;
using MySql.Data.MySqlClient;

namespace MyFunctionApp
{
    public class PostsService
    {
        private readonly MySqlDatabase _MySqlDatabase;

        public PostsService(MySqlDatabase mySqlDatabase)
        {
            _MySqlDatabase = mySqlDatabase;
        }

        [FunctionName("InsertIntoPost")]
        public async Task<IActionResult> InsertIntoPost(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] PostClassObject request,
            ILogger log)
        {
            var cmd = _MySqlDatabase.Connection.CreateCommand() as MySqlCommand;
            cmd.CommandText = @"INSERT INTO PostsTable(ID) VALUES (12345)";

            int rowCount = await cmd.ExecuteNonQueryAsync();
            Console.WriteLine(String.Format("Number of rows inserted={0}", rowCount));

            return (ActionResult)new OkObjectResult(1);
        }
    }
}

我最终将 StartUp.cs 分成了两个文件。现在一切正常!

WebJobsStartup.cs:

using AzureFunctions.Extensions.Swashbuckle;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Hosting;
using System.Reflection;
using MyFunctionApp;

[assembly: WebJobsStartup(typeof(WebJobsStartup))]
namespace MyFunctionApp
{
    public class WebJobsStartup : IWebJobsStartup
    {
        public void Configure(IWebJobsBuilder builder)
        {
            builder.AddSwashBuckle(Assembly.GetExecutingAssembly());
        }
    }

}

MyFunctionAppStartUp.cs:

using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
using System;

[assembly: FunctionsStartup(typeof(MyFunctionApp.MyFunctionAppStartup))]
namespace MyFunctionApp
{
    public class MyFunctionApp : FunctionsStartup
    {
        public override void Configure(IFunctionsHostBuilder builder)
        {
            builder.Services.AddTransient<MySqlDatabase>((s) =>
            {
                return new MySqlDatabase(Environment.GetEnvironmentVariable("MyFunctionApp-DbConn"));
            });
            builder.Services.AddSingleton<ServiceQueries>();
        }
    }
}