依赖注入一旦部署便无法在Azure功能中运行,但可以在本地运行

时间:2019-12-03 17:33:01

标签: c# dependency-injection azure-function-app

我有一个带有公共构造函数的类,该构造函数将SqlConnection作为参数。

private readonly SqlConnection _sqlConnection;

public Sample(SqlConnection sqlConnection)
{
    _sqlConnection = sqlConnection;
}

启动文件中,我正在尝试DI

var sqlConnection = new SqlConnection(Environment.GetEnvironmentVariable("AzureSQLConnection"));

builder.Services.AddSingleton<SqlConnection>(sqlConnection);

它在本地运行,但是在部署到Azure时失败,并显示错误

  

System.InvalidOperationException:无法解析类型的服务   尝试激活时出现“ System.Data.SqlClient.SqlConnection”   'Test.Sample.Sample'。在   Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider   sp,Type type,Type requiredBy,Boolean isDefaultParameterRequired)位于   lambda_method(Closure,IServiceProvider,Object [])在   Microsoft.Azure.WebJobs.Host.Executors.DefaultJobActivator.CreateInstance [T](IServiceProvider   serviceProvider)   C:\ projects \ azure-webjobs-sdk-rqm4t \ src \ Microsoft.Azure.WebJobs.Host \ Executors \ DefaultJobActivator.cs   :37岁   Microsoft.Azure.WebJobs.Host.Executors.DefaultJobActivator.CreateInstance [T](IFunctionInstanceEx   functionInstance)在   C:\ projects \ azure-webjobs-sdk-rqm4t \ src \ Microsoft.Azure.WebJobs.Host \ Executors \ DefaultJobActivator.cs   :32点   Microsoft.Azure.WebJobs.Host.Executors.ActivatorInstanceFactory 1.<>c__DisplayClass1_1.<.ctor>b__0(IFunctionInstanceEx i) at C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Executors\ActivatorInstanceFactory.cs : 20 at Microsoft.Azure.WebJobs.Host.Executors.ActivatorInstanceFactory 1.Create(IFunctionInstanceEx   functionInstance)在   C:\ projects \ azure-webjobs-sdk-rqm4t \ src \ Microsoft.Azure.WebJobs.Host \ Executors \ ActivatorInstanceFactory.cs   :26岁   Microsoft.Azure.WebJobs.Host.Executors.FunctionInvoker`2.CreateInstance(IFunctionInstanceEx   functionInstance)在   C:\ projects \ azure-webjobs-sdk-rqm4t \ src \ Microsoft.Azure.WebJobs.Host \ Executors \ FunctionInvoker.cs   :44岁   Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.ParameterHelper.Initialize()   在   C:\ projects \ azure-webjobs-sdk-rqm4t \ src \ Microsoft.Azure.WebJobs.Host \ Executors \ FunctionExecutor.cs   :846在异步   Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.TryExecuteAsyncCore(IFunctionInstanceEx   functionInstance,CancellationToken cancellingToken)位于   C:\ projects \ azure-webjobs-sdk-rqm4t \ src \ Microsoft.Azure.WebJobs.Host \ Executors \ FunctionExecutor.cs   :117

1 个答案:

答案 0 :(得分:0)

尝试在启动和SqlConnection中检查Test.Sample.Sample classes的名称空间。问题是存在两个几乎具有相同名称的类(Microsoft.Data.SqlClient.SqlConnectionSystem.Data.SqlClient.SqlConnection)。 两个类中的类型必须相同。