Azure / azure-functions-host

The host/runtime that powers Azure Functions
https://functions.azure.com
MIT License
1.93k stars 440 forks source link

Dependency Injection support for Functions #3736

Closed fabiocav closed 5 years ago

fabiocav commented 5 years ago

Meta issue to track exposing first class DI support to end-user functions.

High level list of work items (issue links pending):

mathewc commented 5 years ago

Related PR: https://github.com/Azure/azure-functions-host/pull/2389. I was actually planning on getting to this work soon, because even with the level of DI support we already have, supporting instance methods would allow people to take services on job class construction, would enable instance based function filter implementations, etc.

mwadams commented 5 years ago

Scopes services would be particularly useful. We have had some grumbling on one of our channels about the lack of support for that.

espray commented 5 years ago

@mathewc You can use this until this task is complete - https://github.com/espray/azure-webjobs-sdk-extensions its similar to https://github.com/BorisWilhelms/azure-function-dependency-injection

PureKrome commented 5 years ago

@fabiocav 👋 G'day! I noticed that this issue was re-assigned from S38 -> Triaged. Is there any info you/the AF team can say about:

espray commented 5 years ago

@PureKrome Azure Functions Live - Dec 2018 https://youtu.be/Ti_QEeGmRSo?t=1661

balivo commented 5 years ago

As @espray mention... Attribute Binding is good way to inject services at Functions scope... IMHO a DI maybe make Functions too "weight"... I see Azure Functions a "light-weight" way to make APIs, Serverless and Microservices apps...

PureKrome commented 5 years ago

Azure Functions Live - Dec 2018 https://youtu.be/Ti_QEeGmRSo?t=1661

OK - at the 28:15m mark they start talking about DI (and even reference this GH Issue!) TL;DR;

Q: what's the update on this DI stuff? A: This is still extremely high. We addressed this issue on our last webcast. Unfortunately that ambious goal in the commitment ... we're not going to hit this and the end of this year. Looking at early next year ... i'm hesitant to say ... the first few months of next year we should have DI for c# developers. It was in this sprint ... it's not just blocked by my docs (documentation) absolutely something that's important and a priority.

Attribute Binding is good way to inject services at Functions scope...

That's where I tend to disagree with (at the current time). I've always looked at Attribute Injection as a BadThing ™️ / code smell / hack. Here's some more info to help explain why (for some people like me) cringe at them.

I just felt that there are better ways to do this and those ways should be explored/promoted.

balivo commented 5 years ago

That's where I tend to disagree with (at the current time). I've always looked at Attribute Injection as a BadThing ™️ / code smell / hack. Here's some more info to help explain why (for some people like me) cringe at them.

@PureKrome the blog post have good points but need some updates and tests... Last interaction on content (not comments) is from 2015...

I just felt that there are better ways to do this and those ways should be explored/promoted

I'm totally agree and I don't see Attribute Binding at Azure Functions context only just a DI hack...

As I said, I think put DI at Function is extra weight in a light-weight service...

Inject using Atribute is "sucks" and need more tests... And better ways can be explored/promoted... Maybe DI is the best...

jmezach commented 5 years ago

I know that this isn't quite ready yet, but since Instance methods are now supported with the recent deployment I figured I'd give it a try. From what I can tell it seems to be working quite well already, except for scoped services.

In my project I added a Startup class, that implements IWebJobsStartup and I added the WebJobsStartup assembly level attribute. I also had to switch the target framework to netstandard2.0 to make that work due to #3731, but after that I was able to register services using builder.Services.AddSingleton(), etc.

I also added some scoped services and I added an IServiceScopeFactory parameter to the constructor of the class holding my Azure functions. I then used the CreateScope method to build a scope and then request services from it. However, it seems that the scoped services somehow conflict with how the Azure Functions host is working, since I seem to be getting new instances every time, even within the same scope. Again, I know this isn't quite finished, but this wasn't quite what I was expecting to happen.

vitalybibikov commented 5 years ago

Using [Inject] in Functions makes tests dependent on Injection code. As you have to setup the function before calling it from test.

Currently, I'm using HostBuilder:

In Func App:

    var host = new HostConfigurator()
            .Inject<ServiceToInject>(context);

In Extensions, adding that service:

        public static IHost Setup<T>(this HostConfigurator di, ExecutionContext context)
            where T : class
        {
            var builder = di.BuildHost(context);

            var host = builder.ConfigureServices((hostContext, services) =>
                {
                    services.AddScoped<T>();
                })
                .ConfigureData()
                .Build();

            return host;
        }

Configuring all dependencies, Startup-like, common place:


public static class HostBuilderExtensions
    {
        public static IHostBuilder ConfigureData(this IHostBuilder builder)
        {
            builder.ConfigureServices((hostContext, services) =>
            {
                // here to setup all deps: efcore, options, etc;
            });

            return builder;
        }
    }

And Host Start, run some validation before start:

      public static T StartService<T>(this IHost host)
        {
            // Init code before Start, e.g. AutoMapper validation

            host.Start();
            var service = host.Services.GetService<T>();
            return service;
         }

Definitely, some kind of Startup will save the day, but placing Injection into arguments of the function might not be the best solution.

This one was written before, https://github.com/BorisWilhelms/azure-function-dependency-injection

It

jmezach commented 5 years ago

Any updates on this issue? I've been trying to get ASP.NET Core Health Checks to work within an Azure Function app so that I can provide some visibility into whether my app is working correctly. That sort of kinda works, except when you want to implement a custom health check that relies on other services that are registered with DI.

This seems to stem from the fact that the DefaultHealthCheckService from the Microsoft.Extensions.Diagnostics.HealthChecks NuGet package relies on an IServiceScopeFactory and uses it to create a new dependency injection scope. For some reason, the DefaultHealthCheckService is being created with a different implementation of IServiceScopeFactory than the one I'm getting if I inject that service into my Function class directly. I don't really understand why that happens, but the end result is that when it then tries to create my custom health check instance it is unable to resolve the types since it's no longer attached to the root container.

fabiocav commented 5 years ago

@jmezach we're making some progress on this, but unfortunately, other items have taken precedence. 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.

PureKrome commented 5 years ago

@fabiocav

We'll be in a better position to provide an ETA on that once the last SDK items are completed.

Is there an official place we (the public) can view what the last SDK items are? Is it a single/few GH milestones?

I can't explain how important this is for so many of us (that is, people who I talk to, about AF). It's literally a deal blocker for many of us. I know that sounds lame/weird :(

So having any insight into work items, milestones and dates can give us some hope and transparency - as well help us plan expectations and time frames.

We all do really appreciate the work from you and the team. 🎉 🍰

kemmis commented 5 years ago

Can anyone explain how the upcoming DI functionality will very from using a IWebJobsStartup class implementation and just having it register dependencies on the IWebJobsBuilder's Services (IServiceCollection) property? I'm currently able to register my dependencies this way, and then make my functions' classes non-static, and accept dependencies through their constructors without any extra attributes or anything to specify that the parameters should be injected. Does using IWebJobsStartup class create a dependency on WebJobs stuff that makes the function not a stand-alone serverless function?

fabiocav commented 5 years ago

@PureKrome I'll keep this issue updated as we make progress on those items, so this would be the issue to watch. We're resuming work on that, so you should be more updates here soon.

@kemmis you're already benefiting from some of the work that has been done to complete the feature end-to-end. We've broken this down into smaller items and have been lighting them up as they're completed, non-static classes is one of those items. If what you have is addressing your needs, that's great! That won't change and there's no real downsides to your approach. Eventually, what you'll see is a friendlier (Azure Functions focused) API in addition to additional missing features like scoped services support.

argium commented 5 years ago

Related issue with durable functions.

Called activities fail to rehydrate interface inputs correctly

PureKrome commented 5 years ago

@fabiocav Hi again - got another question re: this ->

  • Proper extensibility model for Functions users: clear extensibility model that does not rely on IWebJobsBuilder and uses the correct scope.

Can we get/do logging in this new model?

Will this new "clear extensible model that does not reply on IWebJobsBuilder enable us to be able to:-

Currently, when I can't seem to do any logging in the IWebJobsStartup Configure method.

Repo to replicate this is here.

fabiocav commented 5 years ago

@PureKrome IWebJobsBuilder exposes an API and functionality that targets WebJobs and extension author scenarios. The goal of this task is to expose a model that is appropriate for Azure Functions scenarios. That does include logging scenarios as well.

We're about to merge some of the SDK changes that will unblock that work (e.g. support for scoped services) and will start the work on that API soon. I'll try to keep this issue updated with the details of what that will look like as we move forward so we can make sure it addresses the scenarios we need, get some feedback and iterate on it.

Adding @brettsam since he'll be heavily involved in that process as well.

PureKrome commented 5 years ago

Thanks @fabiocav (and @brettsam for future work 🍰 ) - My gut feeling here is to wait a wee bit longer for stuff to drop in. I'll go back to a simple background task (yes, this is not a "consumption" solution) as the host and when vNext stuff comes online, I can switch out the hosts and keep my logic (and then hopefully become a "consumption" based host/solution)

Cheers team!

Jaffacakes82 commented 5 years ago

Thanks for the awesome working happening in this repo.

I've bumped into something quite odd this morning, I've got two function apps deployed in Azure with exactly the same code base.

One is running run-time version: 2.0.12342.0, the other is running run-time version: 2.0.12353.0. DI is working in the former, but broken in the latter, resulting in an InvalidOperationException - Unable to bind service for type.

Both function apps have worked previously with DI, so the run-time version has clearly updated itself on one of the function apps.

@fabiocav has something regressed? Is there a way I can explicitly set the run-time version in the second version to the one in the first function so DI works again?

EDIT: I've set the FUNCTIONS_EXTENSION_VERSION setting in the Function application settings to 2.0.12342.0 and DI is now working again.

fbeltrao commented 5 years ago

I have the same issue:

Function code is here: https://github.com/Azure/iotedge-lorawan-starterkit/tree/dev/LoRaEngine/LoraKeysManagerFacade

galvesribeiro commented 5 years ago

Folks! Can anyone share a sample on how to use the "instance" functions with DI?

I can't find any official doc/sample on how to use it. Basically trying to use Microsoft.Extensions.Logging for logs and our own services.

I appreciate any help. Thanks!

kemmis commented 5 years ago

Folks! Can anyone share a sample on how to use the "instance" functions with DI?

I can't find any official doc/sample on how to use it. Basically trying to use Microsoft.Extensions.Logging for logs and our own services.

I appreciate any help. Thanks!

Add an IWebJobStartup class to your project:

// WHY IS THIS FILE HERE?
// https://github.com/Azure/Azure-Functions/issues/972

[assembly: WebJobsStartup(typeof(AzureFunctionsAppStartup))]
namespace Example.AzureFunctionsApp
{
    public class AzureFunctionsAppStartup : IWebJobsStartup
    {
        public void Configure(IWebJobsBuilder builder)
        {
            // register your dependencies via builder.Services
        }
    }
}

Then just use constructor injection in your Functions class(s):

namespace Test.AzureFunctionsApp
{
    public class MyFunction
    {
        private readonly IAzureFunctionsAppService _azureFunctionsAppService;

        public MyFunction(IAzureFunctionsAppService azureFunctionsAppService)
        {
            _azureFunctionsAppService = azureFunctionsAppService;
        }

        [FunctionName("MyFunction")]
        public async Task RunAsync([TimerTrigger("0 */5 * * * *")]TimerInfo myTimer, ILogger log)
        {
            log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
            await _azureFunctionsAppService.RunAsync();
        }
    }
}

(Here IAzureFunctionsAppService is a custom service I made that contains the actual app functionality.)

saeid-p commented 5 years ago

@kemmis does that mean it is not required to mark the function class and the run method as static?

kemmis commented 5 years ago

@kemmis does that mean it is not required to mark the function class and the run method as static?

That is correct. It currently works, but requires the webjob dependent code, and thus isn't the most desirable method of doing this. That's why they are still working on the DI feature for Functions - because it's not currently independent of webjobs. I imagine that in the (hopefully near) future there will be a different place to register your dependencies from how I do it in my example. Maybe something like a Startup.cs class like you see in asp.net core apps.

saeid-p commented 5 years ago

@kemmis does that mean it is not required to mark the function class and the run method as static?

That is correct. It currently works, but requires the webjob dependent code, and thus isn't the most desirable method of doing this. That's why they are still working on the DI feature for Functions - because it's not currently independent of webjobs. I imagine that in the (hopefully near) future there will be a different place to register your dependencies from how I do it in my example. Maybe something like a Startup.cs class like you see in asp.net core apps.

I simply named my class Startup.cs and when it comes around, I'll remove the inheritance from IWebJobsStartup! I rather follow DI and deal with the startup changes later! Thanks a lot!

galvesribeiro commented 5 years ago

I don't think it is working for me:

image

The ILogger which were being injected on the function method was moved to be created on the ctor.

Look at what is printed on the debug console when it on line 26...

Am I missing anything?

galvesribeiro commented 5 years ago

Also, if you inspect the _logger variable you will see that all the log providers registered by the function host are there:

image

kemmis commented 5 years ago

@galvesribeiro So, I think this is one of the features we're waiting on. Here are my thoughts based on some assumptions (since I'm not involved in the dev of this stuff). Take this with a grain of salt - it could all be wrong:

When you run/debug a Function locally, it gets run by a "host" app that simulates the environment that it is intended to run on in Azure. In Visual Studio that host is the Azure Functions and Web Jobs Tools extension. I assume there's one that you're using in VS Code as well. image

Anyway, I assume this host has niceties built in that automatically register ILogger "sinks" which dump your logging into the debug console. I also assume that the tool currently only is programmed to do this for the ILogger that gets injected via the function method, and not the instance constructor.

Thus, at this time, I think you would need to manually register the debug console "sink" within your startup class if you want to see your logging in your console locally. As far as how logging will work within Azure, I'd say there's a 50/50 chance that it might flow into App Insights w/o any custom setup in your startup class. Give it a try. I'm curious to find out.

Hope this helps! Also, if you have any further questions, feel free to email me: rafe AT kemmis DOT info. There's no need for us to clutter up this thread with our troubleshooting of stuff that isn't officially supported yet.

galvesribeiro commented 5 years ago

Hey!

I finally got it to work with the logger:

[assembly: WebJobsStartup(typeof(AzureFunctionsAppStartup))]
namespace GP.Profiles
{
    public class AzureFunctionsAppStartup : IWebJobsStartup
    {
        public void Configure(IWebJobsBuilder builder)
        {
            builder.Services.AddLogging(logging =>
            {
                logging.AddFilter(level => true);
                logging.AddConsole();
            });
        }
    }
}

The important thing is the AddFilter(). Without it, it wont print anything that I want to log. Only the ones provided by the host are printed.

Now it works and I can see the logs on the terminal. Look at the selected line:

image

moklas commented 5 years ago

I was having trouble getting this to work but setting FUNCTIONS_EXTENSION_VERSION to 2.0.12342.0 and updating nuget package microsoft.net.sdk.functions from 1.0.24 to 1.0.26 seems to have solved my issues.

chris-rogala commented 5 years ago

This doesn't appear to be working with ServiceLifetime.Scoped. I created a very simple function using the code below:

  1. Scoped object
using System;

namespace TestingDI
{
    public class ScopedContext
    {
        public Guid Id { get; set; } = Guid.NewGuid();
    }
}
  1. Startup.cs
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Hosting;
using Microsoft.Extensions.DependencyInjection;
using TestingDI;

[assembly: WebJobsStartup(typeof(Startup))]
namespace TestingDI
{
    public class Startup : IWebJobsStartup
    {
        public void Configure(IWebJobsBuilder builder)
        {
            builder.Services.AddScoped<ScopedContext>();
        }
    }
}
  1. Function
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Azure.WebJobs.Host;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;

namespace TestingDI
{
    public class TestingScopedContext
    {
        readonly ScopedContext _scopedContext;
        public TestingScopedContext(ScopedContext scopedContext)
        {
            _scopedContext = scopedContext;
        }
        [FunctionName("TestingScoped")]
        public async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)]HttpRequestMessage req, TraceWriter log)
        {
            return req.CreateResponse(HttpStatusCode.OK, _scopedContext);
        }
    }
}

First call result:

{
    "Id": "d18a4a44-2cb4-43e3-bf12-bd6551c34280"
}

Second call result:

{
    "Id": "d18a4a44-2cb4-43e3-bf12-bd6551c34280"
}

I don't feel like I am missing anything, but maybe I am. Anyone else run into this?

galvesribeiro commented 5 years ago

Idk if scoped services are supported yet. I've only tested transient and singleton.

But I know something isn't working properly on this DI. For example, if you use the new HttpClientFactory, it will not work complaining that the MessageHandlerBuilder is not registered.

If you get the same code and put on any other .Net app but Functions, it just work...

chris-rogala commented 5 years ago

Idk if scoped services are supported yet. I've only tested transient and singleton.

While it does construct the object, it appears to register it like a singleton. Like you said, the transient does work, but it won't help if I have more than one class that needs the same instance for the request/action. I am hoping @fabiocav has some guidance and I am just missing some magic code ;)

tekking commented 5 years ago

@galvesribeiro I ran into the same problem with our azure function. If you are making use of a typed httpClient, I managed to fix it in our situation by adding the following configuration command to the startup class:

builder.Services.Configure<HttpClientFactoryOptions>(nameof(DynamicsHttpClient), options => options.SuppressHandlerScope = true);

(replace "DynamicsHttpClient" by the typed httpClient you are using, this requires microsoft.extensions.http v2.2)

galvesribeiro commented 5 years ago

@tekking thanks, but it doesn't work for me :(

[3/20/19 1:26:36 PM] An unhandled host error has occurred.
[3/20/19 1:26:36 PM] Microsoft.Extensions.DependencyInjection.Abstractions: No service for type 'Microsoft.Extensions.Http.HttpMessageHandlerBuilder' has been registered.
ngruson commented 5 years ago

I got this working with 3 Azure Functions earlier this week. But now it seems broken. Just now deleted everything and redeployed function 1 to see where this goes sideways, but still can't get it to work.

When testing the function from the test pane in the Azure portal, it complains about not having the AutoMapper dependency that should have been added to DI in Startup.cs. My function constructor is taking an instance of IMapper. This used to work smoothly at some point when I updated to Microsoft.NET.Sdk.Functions 1.0.26. Locally in the emulator it's working fine, when I deploy to my resource group it booms on me. Any ideas?

The error: 2019-03-23T09:16:24 Welcome, you are now connected to log-streaming service. 2019-03-23T09:16:30.965 [Error] Executed 'GetProducts' (Failed, Id=051f5abc-ed72-4f12-9ca2-4bb6064ac1d7) System.InvalidOperationException : Unable to resolve service for type 'AutoMapper.IMapper' while attempting to activate 'Webshop.CatalogSystem.AzureFunction.ProductsFunction'. at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp,Type type,Type requiredBy,Boolean isDefaultParameterRequired) at lambda_method(Closure ,IServiceProvider ,Object[] ) at Microsoft.Azure.WebJobs.Host.Executors.DefaultJobActivator.CreateInstance[T](IServiceProvider serviceProvider) at C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Executors\DefaultJobActivator.cs : 42 at Microsoft.Azure.WebJobs.Host.Executors.DefaultJobActivator.CreateInstance[T](IFunctionInstanceEx functionInstance) at C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Executors\DefaultJobActivator.cs : 32 at Microsoft.Azure.WebJobs.Host.Executors.ActivatorInstanceFactory1.<>c__DisplayClass1_1.<.ctor>b__0(IFunctionInstanceEx i) at C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Executors\ActivatorInstanceFactory.cs : 20 at Microsoft.Azure.WebJobs.Host.Executors.ActivatorInstanceFactory1.Create(IFunctionInstanceEx functionInstance) at C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Executors\ActivatorInstanceFactory.cs : 26 at Microsoft.Azure.WebJobs.Host.Executors.FunctionInvoker2.CreateInstance(IFunctionInstanceEx functionInstance) at C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Executors\FunctionInvoker.cs : 44 at Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.ParameterHelper.Initialize() at C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Executors\FunctionExecutor.cs : 845 at async Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.TryExecuteAsyncCore(IFunctionInstanceEx functionInstance,CancellationToken cancellationToken) at C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Executors\FunctionExecutor.cs : 116 `

Startup.cs:

[assembly: WebJobsStartup(typeof(Startup))]
namespace Webshop.CatalogSystem.AzureFunction
{
    public class Startup : IWebJobsStartup
    {
        public void Configure(IWebJobsBuilder builder)
        {
            builder.Services.AddScoped<ServiceFactory>(p => p.GetService);
            builder.Services.Scan(scan => scan
                .FromAssembliesOf(typeof(IMediator), typeof(GetProductsQueryHandler))
                .AddClasses()
                .AsImplementedInterfaces());
            builder.Services.AddAutoMapper(new Type[] { typeof(MappingProfile) });
            builder.Services.AddDbContext<CatalogDbContext>(c =>
                c.UseInMemoryDatabase("Catalog"));
        }
    }
}

EDIT: Setting FUNCTIONS_EXTENSION_VERSION to 2.0.12342.0 in the application settings does work, so I'm using that workaround for now. Thanks @Jaffacakes82 and @fbeltrao for that.

andersdissing commented 5 years ago

Im getting the same error as ngruson. When I deploy my code bit not in the emulator :(

AndeyR commented 5 years ago

Same issue. DI works in the emulator, returns 'Unable to resolve service for type 'XXX'' when published.

kemmis commented 5 years ago

@andeyr see this issue:

https://github.com/Azure/Azure-Functions/issues/972

AndeyR commented 5 years ago

@AndeyR see this issue:

Azure/Azure-Functions#972

Thanks for pointing to that rabbit hole) At the end my issue resolved with downgrading host to 2.0.12342.0 Original issue https://github.com/Azure/azure-functions-host/issues/4203

PureKrome commented 5 years ago

Regardless of fixes and outcomes, it still feels like the current situation is a bit of a frustrating experience with lots of issues.

Just looking forward to this issue getting 100% A1 priority, fixed and released.

🤗 hugs to the team! We're just all passionate. Patience is a virtue.....

fabiocav commented 5 years ago

A follow up... yes, there was a regression introduced with the latest release as part of the change to properly support scoped services, where the underlying SDK changes conflicted with the host configuration and, unfortunately, the test coverage was not sufficient to catch that. The problem has been addressed and is rolling out with the next release.

We've been adding the individual features that make up the broader DI solution independently, which lights up additional scenarios as we go, as we thought that would be nice and enable to unblock more and more scenarios before the full set of changes are done, but have not publicly discussed a lot of those because, until the work is completed, there will be gaps and quirks in the behavior.

The instance class/constructor injection support was one of the things that was discusssed more broadly before everything was baked, and unfortunatly, it was what impacted with the recent changes as we wrap up the remaining work and move towards the finish line. We're taking steps to ensure this won't happen again.

The good news is that with the last set of changes, we've checked of last set of impacful changes needed in the SDK/runtime (reflected in the original issue list). Which brings us much closer to completion.

We appreciate the patience as we work through this. We're trying to complete this as carefully as possible while balancing the work with other key features we're delivering in the coming releases, and while the progress may seem slow, work has been happening across all the different repos and we're now finally bringing this together. (and thanks @PureKrome for always knowing exactly how to get your point across in a positive way!)

PureKrome commented 5 years ago

miantosca commented 5 years ago

@fabiocav - When is functions host release 2.0.12382 rolling out? Is this required to get the scoped services fix made in the functions sdk release 3.0.5 to work? I am running in 2.0.12342.0 in Azure to fix the other issues reported with 2.0.12353 and I am still having trouble with scoped services. As far as the core tools releases the latest 2.4.498 does not include 2.0.12382, it includes the broken DI release of 2.0.12353. Just wanting some guidance when all of these will be synced up.

Jaffacakes82 commented 5 years ago

A follow up... yes, there was a regression introduced with the latest release as part of the change to properly support scoped services, where the underlying SDK changes conflicted with the host configuration and, unfortunately, the test coverage was not sufficient to catch that. The problem has been addressed and is rolling out with the next release.

Following on from the above comment, the latest release of the Azure Functions Core Tools released two days ago comes packaged with the regressed version of the Functions run-time host and also breaks DI locally - it seems to have auto-updated on my machine somehow. Don't upgrade just yet!

@miantosca If you're still having the issue I did the following to resolve npm install -g azure-functions-core-tools@2.4.419 and ensure your launch settings are executing this host. I had multiple installations of the core tools for some reason.

fabiocav commented 5 years ago

2.0.12382 is rolling out to Azure and yes, it is a requirement for the scoped services support recently introduced. The rollout is expected to complete by the end of this week.

Once the Azure deployment is completed, the Core Tools matching that version will be released.

miantosca commented 5 years ago

@fabiocav and team - thanks so much for resolving this

2.0.12382.0 is now a valid version in Azure and the DI issues have been resolved

saeid-p commented 5 years ago

Thanks to @fabiocav and Azure functions team. Now, how to inject the ILogger to the lower services used by the function? BTW, ILogger only gets injected via the run method parameters. The constructor injection doesn't work for ILogger.

nguyenquyhy commented 5 years ago

Thank you very much for resolving this! Our functions are working properly now.