Dumber_Texan2
Dumber_Texan2

Reputation: 978

Can't get Azure Function .Net 5.0 Dependency Injection to inject service in another Project with dependencies

I am trying to inject a Service into my Azure Function that lives in another Project.

Here is my code.

public static async Task Main()
        {
            var host = new HostBuilder()
                .ConfigureFunctionsWorkerDefaults()
                .ConfigureServices(s =>
                {                    
                    s.AddTransient<ILocationService, LocationService>();                    
                })
                .Build();

            Console.WriteLine("Host running!");

            await host.RunAsync();            

        }

The LocationService is dependent on the DBContext.

private readonly MyAppDBContext _context;

        public LocationService(MyAppDBContext context)
        {
            _context = context;
        }

Here is my Function.

private readonly ILocationService _locationService;
private readonly TelemetryClient _telemetryClient;
    
    public Function1(ILocationService locationService, TelemetryConfiguration telemetryConfiguration)
    {
        _locationService = locationService;            
        _telemetryClient = new TelemetryClient(telemetryConfiguration);
    }

Here is the error.

Result: Failure Exception: System.InvalidOperationException: Unable to resolve service for type 'MyApp.Data.MyAppDBContext' while attempting to activate 'MyApp.Services.LocationService'. at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateArgumentCallSites(Type implementationType, CallSiteChain callSiteChain, ParameterInfo[] parameters, Boolean throwIfCallSiteNotFound) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateConstructorCallSite(ResultCache lifetime, Type serviceType, Type implementationType, CallSiteChain callSiteChain) at

I've tried both version 6.0 and 5.0.2 of Microsoft.Extensions.DependencyInjection.

This guide seems to suggest I'm doing it right.

https://learn.microsoft.com/en-us/azure/azure-functions/dotnet-isolated-process-guide#dependency-injection

Any help is much appreciated! Thanks!

Upvotes: 0

Views: 621

Answers (1)

Dumber_Texan2
Dumber_Texan2

Reputation: 978

Turns out that this was an issue with Visual Studio 2019. I couldn't get web publishing to work, so I used FTP. To do that, I used the publish to folder method. I then zipped the files and used Power Shell to upload the zip file. Turns out that the publish to folder method was not working properly. It was never updating the files. All the changes I made never made it to the server. So frustrating! I wasted hours and hours on this. Here is what is now working. I also fixed the web publishing method by downloading a new publish profile.

 s.AddDbContext<MyDBContext>();
 s.AddLogging();
 s.AddScoped<IMyService, MyService>();
 

Upvotes: 0

Related Questions