I've created an Azure Function version 3 using .NET 5 and dependency injection trough the constructor of the class. See dummy code below:
public class MyAzureFunction
{
private readonly IMyRepository _myRepository;
public MyAzureFunction(IMyRepository myRepository)
{
_myRepository = myRepository;
}
[Function("MyAzureFunction")]
public async Task Run([TimerTrigger("0 */15 * * * *")] TimerInfo myTimer, FunctionContext context)
{
ILogger logger = context.GetLogger("MyAzureFunction");
logger.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
List<object> result = await _myRepository.GetAllAsync();
// Keep going...
}
}
Inside the Startup
class the scopes are added.
[assembly: FunctionsStartup(typeof(MyNamespace.Functions.Startup))]
namespace MyNamespace.Functions
{
public class Startup : FunctionsStartup
{
public override void Configure(IFunctionsHostBuilder builder)
{
builder.Services
.AddScoped<IMyRepository, MyRepository>();
}
}
}
The Program file looks as follow:
public class Program
{
public static void Main()
{
IHost host = new HostBuilder()
.ConfigureFunctionsWorkerDefaults()
.Build();
host.Run();
}
}
Inside the .csproj
file stands this line of code:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
<AzureFunctionsVersion>v3</AzureFunctionsVersion>
<OutputType>Exe</OutputType>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Azure.Functions.Extensions" Version="1.1.0" />
<PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.Timer" Version="4.1.0" />
<PackageReference Include="Microsoft.Azure.Functions.Worker.Sdk" Version="1.3.0" />
<PackageReference Include="Microsoft.Azure.Functions.Worker" Version="1.6.0" />
</ItemGroup>
<!-- Skiped some lines -->
</Project>
The problem is when I want to run the Azure Function. I've got this warning:
No job functions found. Try making your job classes and methods public. 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.).
I've tried next things:
I've added
builder.AddTimers()
inside theStartup
class butIFunctionsHostBuilder
contains no definition for it. Even if I addMicrosoft.Azure.Functions.Worker.Extensions.Timer
.Making everything static inside
MyAzureFunction
but don't work because the static constructors can't contain parameters.Also
builder.Services.AddTimers()
(like in the documentation) is not defined.
My question is now how could I use dependency injection using Azure Functions and .NET 5 using the constructor.