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

标签 c# mysql azure azure-functions azure-mysql-database

我创建了一个使用 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>();
        }
    }
}

关于c# - 在 Azure Functions v2 上使用 MySqlDatabase (MySql.Data.MySqlClient) - "Unable to resolve service",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58065078/

相关文章:

azure - 从 Azure VM 访问 Azure 存储,无需出站 Internet

c# - 操作数永不为空警告

c# - 当前上下文中不存在名称 IEnumerator

php - 检查图片是否存在于单独的域中

php - ACF 自定义查询 GET URL

mysql - 交集表上的外键约束

c# - 不再有动态、笨拙的反射?

c# - EPPlus - LoadFromCollection - 文本转换为数字

Windows Azure REST API MediaLink

c# - Swashbuckle - 使用自定义 JSON 模式进行操作