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?