1
votes

Requirement: Create Azure Function which can inject Entity Framework context to Run method using dependency injection.

Here is my Startup class

   [assembly: WebJobsStartup(typeof(Startup))]
   namespace MessagesToSqlDbFuncApp
   {
       internal class Startup : IWebJobsStartup
       {
        public void Configure(IWebJobsBuilder builder) =>
        builder.AddDependencyInjection<ServiceProviderBuilder>();
       }
   }

Here is ServiceProviderBuilder class

public class ServiceProviderBuilder : IServiceProviderBuilder
{
    public IServiceProvider Build()
    {
        IConfigurationRoot config = new ConfigurationBuilder()
            .SetBasePath(Environment.CurrentDirectory)
            .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
            .AddEnvironmentVariables()
            .Build();

        var connectionString = config.GetConnectionString("SqlConnectionString");

        var services = new ServiceCollection();

        services.AddDbContext<DataContext>(options => options.UseSqlServer(connectionString));

        return services.BuildServiceProvider(true);
    }
}

This is my function

   [FunctionName("MessagesToSqlDbFuncApp")]
    public static async Task Run([BlobTrigger("messagecontainer/{name}", Connection = "AzureWebJobsStorage")]
        Stream myBlob, 
        string name, 
        ILogger log,
        [Inject] DataContext myContext)
    {

    }

Here is the error which thrown while running the funciton

[2/20/2019 4:25:10 AM] Error indexing method 'MessagesToSqlDbFuncApp' [2/20/2019 4:25:10 AM] Microsoft.Azure.WebJobs.Host: Error indexing method 'BlobQCMessagesToSqlDbFuncApp'. Microsoft.Azure.WebJobs.Host: Cannot bind parameter 'myContext' to type DataContext. Make sure the parameter Type is supported by the binding. If you're using binding extensions (e.g. Azure Storage, ServiceBus, Timers, etc.) make sure you've called the registration method for the extension(s) in your startup code (e.g. builder.AddAzureStorage(), builder.AddServiceBus(), builder.AddTimers(), etc.).

Here is the nuget packages and versions

  • Azure Function Version : 2
  • Visual Studio : 2017
  • Microsoft.EntityFrameworkCore: 2.1.4
  • Microsoft.EntityFrameworkCore.Design: 2.1.4
  • Microsoft.EntityFrameworkCore.SqlServer: 2.1.4
  • Microsoft.Extensions.DependencyInjection: 2.2.0
  • Microsoft.NET.Sdk.Functions: 1.0.24
  • Microsoft.NETCore.App: 2.1.0

Important Note: Debugger is not hitting the Startup class!. How do I initialize the startup class?

2
I've opened an issue regarding the same (I guess it's the same) problem github.com/Azure/azure-webjobs-sdk/issues/…Andrey Stukalin
Any progress, could you accept one useful solution or simply post yours for others to refer?Jerry Liu
marked the answerkudlatiger

2 Answers

1
votes

Assume you work with the package Willezone.Azure.WebJobs.Extensions.DependencyInjection, right click on your function project, Edit <functionProject>.csproj, and change TargetFramework from netcoreapp2.1 to netstandard2.0.

<TargetFramework>netstandard2.0</TargetFramework>

The inconsistency exists because the unofficial package doesn't catch up the changes in Function SDK, the official guidance is underway.

Most of the core pieces to add this support are done. We'll be in a better position to provide an ETA on that once the last SDK items are completed.

1
votes

There are issues with startup class and azure function. See Azure function Publish not creating Startup class entry in extensions.json

Some of those issues are known limitations of the product at the moment. We are working on first class support for customer facing DI capabilities in Azure Functions, which will come with a full set of documentation, including services you can depend on and official guidance.

One solution is to use IExtensionConfigProvider (see Azure Function run code on startup )

Personally I just ended up using static constructor to do the initialization and use azure function as humble object as describe here : Integrating Simple Injector in Azure Functions

Edit 25/02/2019

The version 1.0.2 of the package Microsoft.Azure.WebJobs.Script.ExtensionsMetadataGenerator fixes the binding issue in extensions.json. The Microsoft.NET.Sdk.Functions should include the latest version of the ExtensionsMetadataGenerator soon.