我创建了一个使用MySql.Data.MySqlClient
依赖项的 Azure Functions 应用 ~v2 项目。
该项目设置为还使用该SwashBuckle
库来创建可调用的 API。
当我从本地设置执行我的项目时,它工作正常。然而,当我将 Functions 应用程序发布到我们的 Azure 服务器并尝试在那里测试该函数时,我收到此错误:
System.InvalidOperationException:尝试激活“MyFunctionApp.PostsService”时,无法解析“MyFunctionApp.MySqlDatabase”类型的服务。
在 Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp,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);
}
}
}