Azure函数和依赖注入

时间:2019-11-13 22:00:11

标签: azure dependency-injection .net-core azure-functions

我的Azure Function v2项目中具有以下Startup类:

[assembly: FunctionsStartup(typeof(AzureAppDomainRegistration.Startup))]
namespace AzureAppDomainRegistration
{
    public class Startup : FunctionsStartup
    {
        public override void Configure(IFunctionsHostBuilder builder)
        {
            var connString = System.Configuration.ConfigurationManager.AppSettings["ConnectionStrings:DataContext"];

            //var connString = config["ConnectionStrings:DataContext"];
            builder.Services.AddDbContext<DataContext>(options => options
                .UseLazyLoadingProxies()
                .UseSqlServer(connString));

            builder.Services.AddTransient<IActionsRegistrationInfo, EfActionsRegistrationInfo>();
        }
    }
}

和功能:

public class Function100_CheckEmail
{
    readonly IActionsRegistrationInfo _actionsRegistrationInfo;

    public Function100_CheckEmail(IActionsRegistrationInfo actionsRegistrationInfo)
    {
        _actionsRegistrationInfo = actionsRegistrationInfo;
    }

    [FunctionName("Function100_CheckEmail")]
    //public static IActionResult Run(
    public async Task<IActionResult> Run(
        [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req,
        [Queue("email-message-admin-confirmation", Connection = "StorageConnectionString")]CloudQueue outputQueue,
        ExecutionContext context,
        ILogger log)
    {
        log.LogInformation("C# HTTP trigger function processed a request.");

但是当执行此功能时,我在Azure Portal上收到以下错误:

enter image description here

没有DI,它可以正常工作。怎么了?

.NET Core 2.2

已添加: 我尝试远程调试器,但我发现Configure文件的Startup方法具有ArgumentNullException例外(由App Insights记录),但没有详细信息。会是什么?

1 个答案:

答案 0 :(得分:-1)

因此,为了在Azure函数中获取环境变量,您需要使用

var connStr =   Environment.GetEnvironmentVariable("ConnectionStrings:SQLConnectionString", EnvironmentVariableTarget.Process);

还要检查local.settings.json中的值是否看起来像这样

{
  "IsEncrypted": false,   
  "Values": {
    "AzureWebJobsStorage": "<connection string>", 
    "AzureWebJobsDashboard": "<connection string>" 
  },
  "Host": {
    "LocalHttpPort": 7071, 
    "CORS": "*" 
  },
  "ConnectionStrings": {
    "SQLConnectionString": "Value"
  }
}

裁判: