VelvetOak5
Azure Functions Dependency Injection "unable to resolve"
Why am I getting
Unable to resolve service for type 'Bugreporter.API.HelloWorld' while attempting to activate 'Bugreporter.API.Function1'.
c#
using System.Text.Json;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.Functions.Extensions;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Extensions.Logging;
namespace Bugreporter.API
{
public class Function1
{
private readonly ILogger<Function1> _logger;
private readonly HelloWorld _helloWorld;
public Function1(HelloWorld helloWorld, ILogger<Function1> logger)
{
_helloWorld = helloWorld;
_logger = logger;
}
[Function("Function1")]
public async Task<IActionResult> TryRun(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req
)
{
_helloWorld.Run();
try
{
...
}
catch (Exception ex)
{
string message = "An unexpected error occurred";
_logger.LogError(ex, message);
return new StatusCodeResult(StatusCodes.Status500InternalServerError);
}
}
}
}
c#
using System.Text.Json;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.Functions.Extensions;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Extensions.Logging;
namespace Bugreporter.API
{
public class Function1
{
private readonly ILogger<Function1> _logger;
private readonly HelloWorld _helloWorld;
public Function1(HelloWorld helloWorld, ILogger<Function1> logger)
{
_helloWorld = helloWorld;
_logger = logger;
}
[Function("Function1")]
public async Task<IActionResult> TryRun(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req
)
{
_helloWorld.Run();
try
{
...
}
catch (Exception ex)
{
string message = "An unexpected error occurred";
_logger.LogError(ex, message);
return new StatusCodeResult(StatusCodes.Status500InternalServerError);
}
}
}
}
c#
using System;
using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
[assembly: FunctionsStartup(typeof(Bugreporter.API.Startup))]
namespace Bugreporter.API;
public class Startup : FunctionsStartup
{
public override void Configure(IFunctionsHostBuilder builder)
{
builder.Services.AddSingleton<HelloWorld>();
}
}
public class HelloWorld
{
...
public void Run()
{
_logger.LogInformation("Hello World");
}
}
c#
using System;
using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
[assembly: FunctionsStartup(typeof(Bugreporter.API.Startup))]
namespace Bugreporter.API;
public class Startup : FunctionsStartup
{
public override void Configure(IFunctionsHostBuilder builder)
{
builder.Services.AddSingleton<HelloWorld>();
}
}
public class HelloWorld
{
...
public void Run()
{
_logger.LogInformation("Hello World");
}
}
1 replies