Giter Site home page Giter Site logo

azure-functions-dotnet-extensions's Introduction

.NET Extensions for Azure Functions

Branch Status
main Build Status

The .NET Extensions for Azure Functions is an open-source, cross-platform set of APIs for commonly used programming patterns and utilities, in Azure Functions.

azure-functions-dotnet-extensions's People

Contributors

brettsam avatar fabiocav avatar liliankasem avatar microsoft-github-policy-service[bot] avatar pragnagopa avatar vrdmr avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

azure-functions-dotnet-extensions's Issues

Load custom configuration file at startup

I have a custom configuration file called appSettings.json and,
now that we are using dependency injection, I want to load it at startup.

before dependency injection my code looked like this:

    public static class Functions
    {
        private const string EveryFiveMinutesCron = "0 */5 * * * *";

        [FunctionName("MyFunction")]
        public static async Task MyFunction([TimerTrigger(EveryFiveMinutesCron)] TimerInfo myTimer, ILogger log, ExecutionContext context)
        {
            var conf = new ConfigurationBuilder()
               .SetBasePath(context.FunctionAppDirectory)
               .AddJsonFile($"appSettings.json", true, true)
               .Build();
        }
    }

now I want to do the same in startup, but I don't have access to the ExecutionContext

[assembly: FunctionsStartup(typeof(Startup))]

namespace MyFunctions
{
    public class Startup : FunctionsStartup
    {
        public override void Configure(IFunctionsHostBuilder builder)
        {
            var appSettings = GetAppSettings();

        }

        private IConfigurationRoot GetAppSettings()
        {
            var rootFolder = Environment.CurrentDirectory;

            var confBuilder = new ConfigurationBuilder()
                .SetBasePath(rootFolder)
                .AddJsonFile("appSettings.json", true, true);

            return confBuilder.Build();
        }
    }
}

I tried many ways to retrieve the FunctionAppDirectory property (mainly through environment variables), but none works once deployed.

How can I retrieve function app directory while at startup ?

FunctionsStartup bypasses host.json

I am just updating a small function app that was created with the VS 2017 template that uses static functions. I had updated my host.json to remove the api prefix:

"extensions": { "http": { "routePrefix": "" } }

As soon as the Startup class is annotated with [assembly: FunctionsStartup(typeof(MyNamespace.Startup))] it ignores this config and the prefix is added.

Should host.json be honoured in this situation or is there an alternative method to affect the api prefix?

Dependency Injection not instantiating instances when using function.json rather than attributes

I've created an Azure Function in C#, and attempting to utilize the dependency injection feature while also defining the Function parameters with a function.json file rather than the .net attributes so that I can use route parameters in the Function methods as described in Customize the HTTP Endpoint.

When I use the HttpTrigger and FunctionName attributes, the dependency injection works as expected. However, when I remove the attributes, and manually define the function.json file, the runtime throws an exception:

System.Private.CoreLib: Exception while executing function: MyClass.myFunction. Anonymously Hosted DynamicMethods Assembly: Object reference not set to an instance of an object.

To be sure, I've copied the automatically generated function.json file when using the attributes in order to ensure I hadn't miss-typed a value somewhere (removed the configurationSource field and ensured my written function.json file is in the output directory)

Versions and other information:
.csproj file sample:

<PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
    <AzureFunctionsVersion>v3</AzureFunctionsVersion>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.Azure.Functions.Extensions" Version="1.1.0" />
    <PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="3.1.16" />
    <PackageReference Include="Microsoft.Extensions.Http" Version="3.1.16" />
    <PackageReference Include="Microsoft.NET.Sdk.Functions" Version="3.0.13" />
  </ItemGroup>

Functions Core Tools:

$ func --version
3.0.3331

I haven't seen a sample of using dependency injection with route parameters, so I may have missed something in the setup. My Startup.cs file matches the example in the Dependency Injection docs.

Happy to provide any other information, or a reproducible example repo if needed.

Azure function v3 fails to start up in Visual Studio 2019 for Mac when using Microsoft.Azure.Functions.Extensions.DependencyInjection

The issue is perfectly reproducible by cloning this repository and running the solution in Visual Studio 2019 for Mac.

When the function starts up the following information is displayed on Terminal:

Azure Functions Core Tools (3.0.2358 Commit hash: d6d66f19ea30fda5fbfe068fc22bc126f0a74168)
Function Runtime Version: 3.0.13159.0

System.Private.CoreLib: Could not load type 'Microsoft.Azure.WebJobs.Hosting.IWebJobsStartup2' from assembly 'Microsoft.Azure.WebJobs.Host, Version=3.0.17.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'.

Further system info:

Operating system: Mac OS Catalina version 10.15.7

=== Visual Studio Community 2019 for Mac ===

Version 8.7.8 (build 4)
Installation UUID: 67aa6aa9-9d70-4bc6-b948-6340f369c763
GTK+ 2.24.23 (Raleigh theme)
Xamarin.Mac 6.18.0.23 (d16-6 / 088c73638)

Package version: 612000093

=== Mono Framework MDK ===

Runtime:
Mono 6.12.0.93 (2020-02/620cf538206) (64-bit)
Package version: 612000093

=== Roslyn (Language Service) ===

3.7.0-6.20427.1+18ede13943b0bfae1b44ef078b2f3923159bcd32

=== NuGet ===

Version: 5.7.0.6702

=== .NET Core SDK ===

SDK: /usr/local/share/dotnet/sdk/3.1.402/Sdks
SDK Versions:
3.1.402
3.1.401
MSBuild SDKs: /Library/Frameworks/Mono.framework/Versions/6.12.0/lib/mono/msbuild/Current/bin/Sdks

=== .NET Core Runtime ===

Runtime: /usr/local/share/dotnet/dotnet
Runtime Versions:
3.1.8
3.1.7
2.1.22
2.1.21

=== Xamarin.Profiler ===

'/Applications/Xamarin Profiler.app' not found

=== Updater ===

Version: 11

=== Apple Developer Tools ===

A valid Xcode installation was not found at the configured location: '/Applications/Xcode.app'

=== Xamarin.Mac ===

Xamarin.Mac not installed. Can't find /Library/Frameworks/Xamarin.Mac.framework/Versions/Current/Version.

=== Xamarin.iOS ===

Xamarin.iOS not installed.
Can't find mtouch or the Version file at /Library/Frameworks/Xamarin.iOS.framework/Versions/Current.

=== Xamarin Designer ===

Version: 16.7.0.495
Hash: 03d50a221
Branch: remotes/origin/d16-7-vsmac
Build date: 2020-08-28 13:12:52 UTC

=== Xamarin.Android ===

Not Installed

=== Microsoft OpenJDK for Mobile ===

Java SDK: Not Found

Android Designer EPL code available here:
https://github.com/xamarin/AndroidDesigner.EPL

=== Android SDK Manager ===

Version: 16.7.0.13
Hash: 8380518
Branch: remotes/origin/d16-7~2
Build date: 2020-09-16 05:12:24 UTC

=== Android Device Manager ===

Version: 16.7.0.24
Hash: bb090a3
Branch: remotes/origin/d16-7
Build date: 2020-09-16 05:12:46 UTC

=== Build Information ===

Release ID: 807080004
Git revision: 9ea7bef96d65cdc3f4288014a799026ccb1993bc
Build date: 2020-09-16 17:22:54-04
Build branch: release-8.7
Xamarin extensions: 9ea7bef96d65cdc3f4288014a799026ccb1993bc

=== Operating System ===

Mac OS X 10.15.7
Darwin 19.6.0 Darwin Kernel Version 19.6.0
Mon Aug 31 22:12:52 PDT 2020
root:xnu-6153.141.2~1/RELEASE_X86_64 x86_64

Error "The binding type(s) 'blobTrigger' are not registered." after update of SDK.Functions to 3.0.4

Getting en error "The binding type(s) 'blobTrigger' are not registered. Please ensure the type is correct and the binding extension is installed."
after update of SDK.Functions to 3.0.4.
Even a most simple setup like this fails:

        public static void Run([BlobTrigger("samples-workitems/{name}", Connection = "AzureWebJobsStorage")]Stream myBlob, string name, ILogger log)
        {
            log.LogInformation($"C# Blob trigger function Processed blob\n Name:{name} \n Size: {myBlob.Length} Bytes");
        }

[Feature Request] Specify Startup per function

Hello,

I am wondering if it would be a good option to be able to specify or decorate a function to tell it which startup it should use.

The usecase of this is if we have a single function project which multiple functions inside, they are all related but some of these does not need any of the DI configuration some of the others have, so it would be nice to be able to provide a FuncationAStartup and FunctionXStartup.

Multiple Azure functions ?

hello,

I have 4 azure functions in the same project, so they share the same host.
I wanted to use dependency injection to manage services but I realize that when you specify singleton then the instance is shared between all Azure functions.

Is there a level of isolation that would allow to have a singleton by Azure function without being forced to use the "scoped" level that is by invocation?

Thank you,

Dependency injection based on trigger parameter

My function is part of a multi-tenant solution so it needs to connect to multiple databases based on the Message headers from Even Bus. So in order to inject a proper Repository class I need to get the tenant id from the message. Is there a way to resolve a dependence by accessing a Message before function execution.

Here's a sample to visualize the problem :

[FunctionName("DonationEventFunction")]
public async static void Run(
            [ServiceBusTrigger("topic", "subscription", Connection = "EventBusConn")] Message message,
            ILogger log,
            IConfiguration configuration,

            **IRepository repo**
)
        {
                // ideally I'd like to have IRepository injected in FunctionsStartup however that is not possible as I need to get tenant id from message.

              // this is what I have to do now .... but this makes DI impossible 
              var tenantId = message.GetTenantId();
              var repo = new SqlRepoImplementation(tenantId).
        }

So I am looking to see if there's a way to access message and inject the repo before function is executed.

Microsoft.Extensions.DependencyInjection.Abstractions: Unable to resolve service for type

I am receiving the next error when running the Basic Demo:

[5/23/2019 12:38:21 PM] Executed 'SampleFunction' (Failed, Id=d27a090a-4ddf-4e5c-92e6-660646c81be9)
[5/23/2019 12:38:21 PM] Microsoft.Extensions.DependencyInjection.Abstractions: Unable to resolve service for type 'Microsoft.Azure.Functions.Samples.DependencyInjectionBasic.IGreeter' while attempting to activate 'Microsoft.Azure.Functions.Samples.DependencyInjectionBasic.SampleFunction'.
[5/23/2019 12:38:22 PM] An unhandled host error has occurred.
[5/23/2019 12:38:22 PM] Microsoft.Extensions.DependencyInjection.Abstractions: Unable to resolve service for type 'Microsoft.Azure.Functions.Samples.DependencyInjectionBasic.IGreeter' while attempting to activate 'Microsoft.Azure.Functions.Samples.DependencyInjectionBasic.SampleFunction'.

What am I missing?

Registering implementation type X is not assignable to service type IX when using Generics

is this a known issue limitation?

I have added code to reproduce it here: https://github.com/ruslanss/azure-functions-dotnet-extensions/tree/service_registration_bug

this type of service registration doesn't appear to be supported:

builder.Services.AddSingleton<IValidator<WhateverCommand>, NullValidator>();

Error on host startup:

[2020-10-22T20:12:11.169] A host error has occurred during startup operation '3a905cf7-b8f9-4dad-868a-ae23c7e8c1db'.
[2020-10-22T20:12:11.170] Microsoft.Azure.WebJobs.Script.WebHost: Registering implementation type Microsoft.Azure.Functions.Samples.DependencyInjectionBasic.InjectionTest.NullValidator is not assignable to service type Microsoft.Azure.Functions.Samples.DependencyInjectionBasic.InjectionTest.IValidator<Microsoft.Azure.Functions.Samples.DependencyInjectionBasic.InjectionTest.WhateverCommand>.

Adding AspNetCore.Identity packages causes runtime error

(or any other package)

Cause the following as soon asi t's included in a Azure Functions V3 project. (litterally created new from vs code set to v3 using C#)

The 'HttpTriggerCSharp' function is in error: Microsoft.Azure.WebJobs.Host: Error indexing method 'HttpTriggerCSharp'. Microsoft.Azure.WebJobs.Host: Cannot bind parameter 'log' to type ILogger. 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's my csproj:

netcoreapp3.0 v3 Azure_Functions_Test PreserveNewest PreserveNewest Never

Doesn't matter if I'm using DI or not.

Upgrading Microsoft.Extensions.DependencyInjection.Abstractions to latest version (5.0.0) breaks DI

Is there a reason this package references such an old version of the DI extensions?

This package references 2.1.0:

<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="2.1.0" />

when the latest version of this package is 5.0.1. 2.1.0 is from 2018!

I had a transitive dependency to this package and upgraded it as it was out of date and this seems to have broken DI.

Can this dependency get updated to the latest version please?

Sample for using ConfigurationBuilder as well?

How do you handle the ConfigurationBuilder with this DI approach now that the function itself is not static, but a class getting constructor injection?

var config = new ConfigurationBuilder() .SetBasePath(context.FunctionAppDirectory) .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true) .AddEnvironmentVariables() .Build();

UserSecretsId causing Microsoft.Extensions.DependencyInjection.Abstractions: Unable to resolve service for type X while attempting to activate Function.Y

After publishing to Azure via VS2019 user secrets is populated as below

<PropertyGroup>
	<TargetFramework>netcoreapp3.1</TargetFramework>
	<AzureFunctionsVersion>v3</AzureFunctionsVersion>
	<UserSecretsId>f360954f....</UserSecretsId>
</PropertyGroup> 

Which is causing
Microsoft.Extensions.DependencyInjection.Abstractions: Unable to resolve service for type 'Interface' while attempting to activate 'Function'
Only seems to occur for services injected into dependent class libraries (Common) in this case. Removing UserSecretsId and it works fine.

Full broken .csproj

<Project Sdk="Microsoft.NET.Sdk">
	<PropertyGroup>
		<TargetFramework>netcoreapp3.1</TargetFramework>
		<AzureFunctionsVersion>v3</AzureFunctionsVersion>
		<UserSecretsId>f360954f... etc</UserSecretsId>
	</PropertyGroup>
	<ItemGroup>
		<PackageReference Include="FluentValidation" Version="9.0.0" />
		<PackageReference Include="Microsoft.Azure.Functions.Extensions" Version="1.0.0" />
		<PackageReference Include="Microsoft.NET.Sdk.Functions" Version="3.0.3" /> 
	</ItemGroup>
	<ItemGroup>
		<ProjectReference Include="..\Common\Common.csproj" />
	</ItemGroup>
	<ItemGroup>
		<None Update="host.json">
			<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
		</None>
		<None Update="local.settings.json">
			<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
			<CopyToPublishDirectory>Never</CopyToPublishDirectory>
		</None>
	</ItemGroup>
</Project>

dependency injection exception instead of null

we try to add azure functions support to a graphql library which usually runs in asp.net core. this library strongly builds on top of the microsoft dependency injection. a lot of things work very smoothly but there are some issues with the way this extension throws exceptions instead of returning null.

i created a reproduction which demonstrates this issue. the code is at https://github.com/OneCyrus/AzF-DependencyInjection-Repro and it features a simple asp.net core webapi which returns a string "still works" (http://localhost:5000/api/inject)

there's also an azure function which does the same but throws an exception and only returns a 500 server error (http://localhost:7071/api/Inject).

I've also created an additional demo which shows the different behaviour of the DI in asp.net core with GetService and GetRequiredService. (http://localhost:5000/api/injectAdv)

Could not load type 'Microsoft.Azure.WebJobs.Hosting.IWebJobsStartup2'

When I install azure-functions-dotnet-extensions to be able to do a Startup class.

The error i got is:

System.Private.CoreLib: Could not load type 'Microsoft.Azure.WebJobs.Hosting.IWebJobsStartup2' from assembly 'Microsoft.Azure.WebJobs.Host, Version=3.0.17.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'

But the project reference is poiting to 3.0.18.0.

image

I'm having this problem on mac.

Inject ILogger in a service.

Is it somehow possible to inject the ILogger into the constructor of a Service? I rather not pass on the instance, especially not when I have a multi layer (service / repository) pattern.

Dependencies of scoped services are resolved from the root container and become singletons

We came across this issue when using MediatR within a function.
The issue seems to be that when you resolve a service from a scope and the service that service itself has dependencies, then those dependencies are not being resolved from the scope, as would be expected, but are being resolved from the root container. That turns those dependencies into singletons.

The following code sample illustrates the problem. It is a simplified version of what happens in MediatR.Extensions.Microsoft.DependencyInjection:

`
using System;
using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.Azure.WebJobs;
using Microsoft.Extensions.DependencyInjection;

[assembly: FunctionsStartup(typeof(FunctionAppDiTest.Startup))]
namespace FunctionAppDiTest
{
public class Startup : FunctionsStartup
{
public override void Configure(IFunctionsHostBuilder builder)
{
builder.Services.AddTransient(p => p.GetService);
builder.Services.AddScoped<IMyService, MyService>();
builder.Services.AddScoped<IMyDependency, MyDependency>();
}
}

public class Function1
{
    private readonly IServiceProvider _serviceProvider;

    public Function1(IServiceProvider serviceProvider)
    {
        _serviceProvider = serviceProvider;
    }

    [FunctionName("Function1")]
    public void Run([TimerTrigger("*/10 * * * * *")]TimerInfo myTimer)
    {
        IMyService svc1, svc2;
        IMyDependency dep1, dep2;
        using (var scope = _serviceProvider.CreateScope())
        {
            svc1 = scope.ServiceProvider.GetService<IMyService>();
            dep1 = svc1.MyDependency;
        }
        using (var scope = _serviceProvider.CreateScope())
        {
            svc2 = scope.ServiceProvider.GetService<IMyService>();
            dep2 = svc2.MyDependency;
        }

        if (ReferenceEquals(svc1, svc2))
            throw new Exception("Service instances from 2 different scopes should not be the same!");

        if (ReferenceEquals(dep1, dep2))
            throw new Exception("Dependency instances from 2 different scopes should not be the same!");
    }
}
public delegate object ServiceFactory(Type type);

public class MyService : IMyService
{
    public MyService(ServiceFactory serviceFactory)
    {
        MyDependency = (IMyDependency)serviceFactory(typeof(IMyDependency));
    }

    public IMyDependency MyDependency { get; }
}

public interface IMyService
{
    IMyDependency MyDependency { get; }
}

public class MyDependency : IMyDependency
{
}

public interface IMyDependency
{
}

}
`

The resulting instances of svc1 and svc2 are not the same, but those of dep1 and dep2 are.
If you put a breakpoint in the lambda "p=>p.GetService" and mark the instance of "p" you will notice that both times the same instance of the ServiceProvider is used.
This probably is also the root cause of #19.

Microsoft.Azure.Functions.Extensions should requires same package version as webjobs SDK

Right now this extension requires Microsoft.Extensions.DependencyInjection >= 2.2.0, this prevent using a dependency which has a requirements for version 2.1.0 of the same package.
Currently the webjobs SDK has dependencies to versions 2.1.0 for Microsoft.Extensions.* packages.

Is this dependency to 2.2.0 a real requirement as the webjobs SDK does not even require it?

Microsoft.NET.Sdk.Functions > 3.0.3 publish skips lots of DLLs

I just upgraded my Visual Studio Azure Function project to use Microsoft.NET.Sdk.Functions 3.0.6. It seems that DLL dependencies aren't copied to the output folder on publish.

Here's the dependency list when publishing with 3.0.3:
ExcelDataReader.DataSet.dll ExcelDataReader.dll Isopoh.Cryptography.Argon2.dll Isopoh.Cryptography.Blake2b.dll Isopoh.Cryptography.SecureArray.dll Microsoft.ApplicationInsights.dll Microsoft.AspNetCore.Authentication.Abstractions.dll Microsoft.AspNetCore.Authentication.Core.dll Microsoft.AspNetCore.Authorization.dll Microsoft.AspNetCore.Authorization.Policy.dll Microsoft.AspNetCore.Connections.Abstractions.dll Microsoft.AspNetCore.Hosting.Abstractions.dll Microsoft.AspNetCore.Hosting.Server.Abstractions.dll Microsoft.AspNetCore.Http.Abstractions.dll Microsoft.AspNetCore.Http.Connections.Client.dll Microsoft.AspNetCore.Http.Connections.Common.dll Microsoft.AspNetCore.Http.dll Microsoft.AspNetCore.Http.Extensions.dll Microsoft.AspNetCore.Http.Features.dll Microsoft.AspNetCore.JsonPatch.dll Microsoft.AspNetCore.Mvc.Abstractions.dll Microsoft.AspNetCore.Mvc.Core.dll Microsoft.AspNetCore.Mvc.Formatters.Json.dll Microsoft.AspNetCore.Mvc.WebApiCompatShim.dll Microsoft.AspNetCore.ResponseCaching.Abstractions.dll Microsoft.AspNetCore.Routing.Abstractions.dll Microsoft.AspNetCore.Routing.dll Microsoft.AspNetCore.SignalR.Client.Core.dll Microsoft.AspNetCore.SignalR.Client.dll Microsoft.AspNetCore.SignalR.Common.dll Microsoft.AspNetCore.SignalR.Protocols.Json.dll Microsoft.AspNetCore.WebUtilities.dll Microsoft.Azure.WebJobs.dll Microsoft.Azure.WebJobs.Extensions.dll Microsoft.Azure.WebJobs.Extensions.Http.dll Microsoft.Azure.WebJobs.Extensions.Storage.dll Microsoft.Azure.WebJobs.Host.dll Microsoft.Azure.WebJobs.Host.Storage.dll Microsoft.Build.Framework.dll Microsoft.Build.Utilities.Core.dll Microsoft.DotNet.PlatformAbstractions.dll Microsoft.Extensions.Caching.Abstractions.dll Microsoft.Extensions.Caching.Memory.dll Microsoft.Extensions.Configuration.Abstractions.dll Microsoft.Extensions.Configuration.Binder.dll Microsoft.Extensions.Configuration.dll Microsoft.Extensions.Configuration.EnvironmentVariables.dll Microsoft.Extensions.Configuration.FileExtensions.dll Microsoft.Extensions.Configuration.Json.dll Microsoft.Extensions.DependencyInjection.Abstractions.dll Microsoft.Extensions.DependencyInjection.dll Microsoft.Extensions.DependencyModel.dll Microsoft.Extensions.FileProviders.Abstractions.dll Microsoft.Extensions.FileProviders.Physical.dll Microsoft.Extensions.FileSystemGlobbing.dll Microsoft.Extensions.Hosting.Abstractions.dll Microsoft.Extensions.Hosting.dll Microsoft.Extensions.Logging.Abstractions.dll Microsoft.Extensions.Logging.Configuration.dll Microsoft.Extensions.Logging.dll Microsoft.Extensions.ObjectPool.dll Microsoft.Extensions.Options.ConfigurationExtensions.dll Microsoft.Extensions.Options.dll Microsoft.Extensions.Primitives.dll Microsoft.IdentityModel.JsonWebTokens.dll Microsoft.IdentityModel.Logging.dll Microsoft.IdentityModel.Tokens.dll Microsoft.Net.Http.Headers.dll Microsoft.Win32.SystemEvents.dll Microsoft.WindowsAzure.Storage.dll NCrontab.Signed.dll Newtonsoft.Json.Bson.dll Newtonsoft.Json.dll StrexGateway.dll System.Configuration.ConfigurationManager.dll System.Data.SqlClient.dll System.Drawing.Common.dll System.IdentityModel.Tokens.Jwt.dll System.IO.Pipelines.dll System.Net.Http.Formatting.dll System.Security.Cryptography.Pkcs.dll System.Security.Cryptography.ProtectedData.dll System.Security.Cryptography.Xml.dll System.Security.Permissions.dll System.Windows.Extensions.dll
Here's the same list publishing with 3.0.6:
ExcelDataReader.DataSet.dll ExcelDataReader.dll Isopoh.Cryptography.Argon2.dll Isopoh.Cryptography.Blake2b.dll Isopoh.Cryptography.SecureArray.dll Microsoft.ApplicationInsights.dll Microsoft.AspNetCore.Http.Connections.Client.dll Microsoft.AspNetCore.SignalR.Client.Core.dll Microsoft.AspNetCore.SignalR.Client.dll Microsoft.Azure.WebJobs.Extensions.Storage.dll Microsoft.Build.Utilities.Core.dll Microsoft.IdentityModel.JsonWebTokens.dll Microsoft.Win32.SystemEvents.dll Microsoft.WindowsAzure.Storage.dll NCrontab.Signed.dll System.Data.SqlClient.dll System.Drawing.Common.dll System.Windows.Extensions.dll

Add logging services -- AddDebug

Not able to add logger. Added the Microsoft.Extensions.Logging.Debug NuGet. When adding the Debug Logging the host ends up throwing a Null Reference exception.

builder.Services.AddLogging(lb =>
{
  lb.AddDebug();
});

async version of FunctionsStartup

I have code which was written async first in my FunctionsStartup.Configure method. I would rather not transition from sync to async and back again if I can avoid it.

Similar to the introduction of async Main methods, would it be possible to introduce an async Configure method in FunctionsStartup?

Cryptic error messages when using FunctionsStartup DI if DI fails.

When there is an error with the DI setup I am getting a verry cryptic error message that is not really helping to find the cause of actual issue. (local development)

Anonymously Hosted DynamicMethods Assembly: Object reference not set to an instance of an object.
If I wrap repro code in a custom serviceprovider I i can see the actual issue:
Microsoft.Extensions.DependencyInjection: Unable to resolve service for type 'System.Int32' while attempting to activate 'FunctionApp2Injection2.Test'. Now of course in the attached example its trivial to see what goes wrong, but for a somewhat larger dependency tree its hard to find the root cause with such a cryptic error message. Unless the actual error is stored somewhere I am unable to find...

Attached is an example showing both situations.
FunctionApp2Injection2.zip
It can be run locally to get the errors.

Getting error after update of SDK.Functions to 3.0.5

It was working fine the other night until I updated Microsoft.NET.SDK.Functions nuget package to 3.0.4
Currently getting the error Microsoft.Extensions.DependencyInjection.Abstractions: Unable to resolve service for type while trying to activate function

My Setup:

MacOS 10.15.3
.NET Core 3.1.102
Visual Studio Code
func cli 3.0.2245

Related

As pointed out in #36 , func start --build can be used as an alternative. Unfortunately this isn't the case.

[FEATURE REQ] Fluent Strongly Typed Context

We have two problems with C# sdk
1- It is not strongly typed
2- It is unreadable, long methods and too much attributes

Suggestion suppose people to put Activities in interface or class. the the IDurableOrchestrationContext should be able to produce proxy for strongly typed methods

let's instead of

class ActivityClass
{
    [FunctionName(nameof(MethodName))]
    public Task<string> MethodName(int x)
}
//orchestrator
context.CallActivityWithRetryAsync<T>(nameof(ActivityClass.MethodName), retryOptions, input);

We should be able to do:

class ActivityClass
{
    public Task<string> MethodName(int x)
}
//orchestrator
context.ClientOf<AcitivyClass>().WithRetry(retryOptions).MethodName(10);

Will be great

Method not foundMicrosoft.Azure.Functions.Extensions.DependencyInjection.IFunctionsHostBuilder.get_Services() since .Net Core 3.1 release

Hi,

When updating our nuget packages like
Microsoft.Extensions.DependencyInjection.Abstractions
and
Microsoft.Extensions.Configuration
to version 3.1.0 released with .Net Core 3.1 yesterday, the Function host fails to start with the following error : Method not found: 'Microsoft.Extensions.DependencyInjection.IServiceCollection Microsoft.Azure.Functions.Extensions.DependencyInjection.IFunctionsHostBuilder.get_Services()'

I'm using the latest VS version, 16.4.0 and the v3 preview function runtime.

Thanks,
Frank

Request: a simple README.MD for the "Scopes" example, explaining what is EXPECTED when people hit the HTTP trigger

👋 Heya - just looking at the "Scopes" sample provided and I'm trying to understand the difference between transient and scoped life's with respect to Azure Functions. I totally grok it, with respect to an ASP.NET Core app + Request/Responses, etc.

It would be really nice if we could have a README.MD added to the scopes folder with example instructions & output. For example, the code says:

// Register MyServiceA as transient.
// A new instance will be returned every
// time a service request is made
builder.Services.AddTransient<MyServiceA>();

// Register MyServiceB as scoped.
// The same instance will be returned
// within the scope of a function invocation
builder.Services.AddScoped<MyServiceB>();

and the output for 1x HTTP request is:

{
"providersMatch": true,
"globalId": "db295a09-5458-4a60-a17e-ea538db8a586",
"serviceAId": "1678107f-c2e4-47eb-9514-0be4af5165dd",
"serviceBId": "1678107f-c2e4-47eb-9514-0be4af5165dd"
}

But I would have thought that serviceAId and serviceBId should be different?

So it would be really nice to explain how to see:

  • a transient in action
  • a scoped in action
  • a singleton in action

with steps showing how to replicate and confirm this is occurring.

🙏 @fabiocav 🙏

NullReferenceException with 1.1.0 (Value cannot be null. (Parameter 'webJobsBuilderContext')

Hello,

After upgrading to the version 1.1.0 of Microsoft.Azure.Functions.Extensions I'm getting a NullReferenceException when I try to start a function app from a Webjob project (I use this for starting the function app in tests)

Here a .zip with 2 projects to reproduce the problem
repro.zip

Unhandled exception. System.ArgumentNullException: Value cannot be null. (Parameter 'webJobsBuilderContext')
   at Microsoft.Azure.Functions.Extensions.DependencyInjection.FunctionsHostBuilderContext..ctor(WebJobsBuilderContext webJobsBuilderContext)
   at Microsoft.Azure.Functions.Extensions.DependencyInjection.DefaultFunctionsHostBuilderContext..ctor(WebJobsBuilderContext webJobsBuilderContext)
   at Microsoft.Azure.Functions.Extensions.DependencyInjection.FunctionsHostBuilder..ctor(IServiceCollection services, WebJobsBuilderContext webJobsBuilderContext)
   at Microsoft.Azure.Functions.Extensions.DependencyInjection.FunctionsStartup.Configure(WebJobsBuilderContext context, IWebJobsBuilder builder)
   at Microsoft.Azure.WebJobs.WebJobsBuilderExtensions.ConfigureStartup(IWebJobsStartup startup, WebJobsBuilderContext context, IWebJobsBuilder builder) in C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Hos
ting\WebJobsBuilderExtensions.cs:line 168
   at Microsoft.Azure.WebJobs.WebJobsBuilderExtensions.UseWebJobsStartup(IWebJobsBuilder builder, Type startupType, WebJobsBuilderContext context, ILoggerFactory loggerFactory) in C:\projects\azure-webjobs-sdk-rqm4t\src\Microsof
t.Azure.WebJobs.Host\Hosting\WebJobsBuilderExtensions.cs:line 111
   at Microsoft.Azure.WebJobs.WebJobsBuilderExtensions.UseWebJobsStartup(IWebJobsBuilder builder, Type startupType, ILoggerFactory loggerFactory) in C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Hosting\We
bJobsBuilderExtensions.cs:line 84
   at Microsoft.Azure.WebJobs.WebJobsBuilderExtensions.UseWebJobsStartup[T](IWebJobsBuilder builder, ILoggerFactory loggerFactory) in C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Hosting\WebJobsBuilderExt
ensions.cs:line 74
   at Microsoft.Azure.WebJobs.WebJobsBuilderExtensions.UseWebJobsStartup[T](IWebJobsBuilder builder) in C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Hosting\WebJobsBuilderExtensions.cs:line 69
   at test.Program.<>c.<Main>b__0_0(IWebJobsBuilder webJobsBuilder) in D:\dev\git\rider\repro-jetbrains\ConsoleApplication2\test\Program.cs:line 39
   at Microsoft.Extensions.Hosting.WebJobsHostBuilderExtensions.<>c__DisplayClass2_0.<ConfigureWebJobs>b__0(HostBuilderContext context, IWebJobsBuilder b) in C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\H
osting\WebJobsHostBuilderExtensions.cs:line 27
   at Microsoft.Extensions.Hosting.WebJobsHostBuilderExtensions.<>c__DisplayClass5_0.<ConfigureWebJobs>b__1(HostBuilderContext context, IServiceCollection services) in C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJ
obs.Host\Hosting\WebJobsHostBuilderExtensions.cs:line 56
   at Microsoft.Extensions.Hosting.HostBuilder.CreateServiceProvider()
   at Microsoft.Extensions.Hosting.HostBuilder.Build()
   at test.Program.Main(String[] args) in D:\dev\git\rider\repro-jetbrains\ConsoleApplication2\test\Program.cs:line 45
   at test.Program.<Main>(String[] args)

The problem seems to come from FunctionsStartup that now implements IWebJobsStartup2
So when building the host:

			var builder = new HostBuilder()
				.UseEnvironment(environment)
				.ConfigureWebJobs(webJobsBuilder =>
				{
					webJobsBuilder
						.AddAzureStorageCoreServices()
						.UseWebJobsStartup<Startup>();
				})

.UseWebJobsStartup<Startup>() will ends up calling with context = null

        private static void ConfigureStartup(IWebJobsStartup startup, WebJobsBuilderContext context, IWebJobsBuilder builder)
        {
            if (startup is IWebJobsStartup2 startup2)
            {
                startup2.Configure(context, builder);
            }
            else
            {
                startup.Configure(builder);
            }
        }

and then crash in constructor of FunctionsHostBuilder

on this line

      this.Context = (FunctionsHostBuilderContext) new DefaultFunctionsHostBuilderContext(webJobsBuilderContext);

example does not work

I came here from

https://docs.microsoft.com/en-us/azure/azure-functions/functions-dotnet-dependency-injection

The related example does not work with the following error:

Method not found: 'Microsoft.Extensions.DependencyInjection.IServiceCollection 
Microsoft.Azure.Functions.Extensions.DependencyInjection.IFunctionsHostBuilder.get_Services()'.

The error looks like this

[10/3/2020 19:15:45] Building host: startup suppressed: 'False', configuration suppressed: 'False', startup operation id: 'a86e9ee9-9a4c-4960-9ad9-9cb89b1266f6'
[10/3/2020 19:15:45] Reading host configuration file 'C:\Users\lazaro\source\repos\WealFunction\WealFunction\bin\Debug\netcoreapp2.1\host.json'
[10/3/2020 19:15:45] Host configuration file read:
[10/3/2020 19:15:45] {
[10/3/2020 19:15:45]   "version": "2.0"
[10/3/2020 19:15:45] }
[10/3/2020 19:15:45] Reading functions metadata
[10/3/2020 19:15:45] 1 functions found
[10/3/2020 19:15:45] Loading startup extension 'Startup'
[10/3/2020 19:15:45] Loaded extension 'Startup' (1.0.0.0)
[10/3/2020 19:15:45] A host error has occurred during startup operation 'a86e9ee9-9a4c-4960-9ad9-9cb89b1266f6'.
[10/3/2020 19:15:45] WealFunction: Method not found: 'Microsoft.Extensions.DependencyInjection.IServiceCollection Microsoft.Azure.Functions.Extensions.DependencyInjection.IFunctionsHostBuilder.get_Services()'.

This is my startup

using System;
using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using WealFunction.Abstract;
using WealFunction.Data;
using WealFunction.Models.Entities;

// Fix this error:
// Method not found: 'Microsoft.Extensions.DependencyInjection.IServiceCollection
// Microsoft.Azure.Functions.Extensions.DependencyInjection.IFunctionsHostBuilder.get_Services()'.
[assembly: FunctionsStartup(typeof(WealFunction.Startup))]

namespace WealFunction
{
    public class Startup : FunctionsStartup
    {
        public override void Configure(IFunctionsHostBuilder builder)
        {
            builder.Services.AddTransient<User>();
        }

    } // class
}

An this is the related funcion:

using System;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.Extensions.Logging;
using WealFunction.Abstract;
using WealFunction.Data;
using WealFunction.Models;
using WealFunction.Models.Entities;

namespace WealFunction.Functions
{
    public class AnnualInterestRate
    {
        private readonly IRepository<User> _userIdal;

        public AnnualInterestRate(IRepository<User> userIdal)
        {
            _userIdal = userIdal;
        }

        [FunctionName("AnnualInterestRate")]
        public void Run([TimerTrigger("0 30 11 * * *", RunOnStartup = true)]TimerInfo myTimer)
        {
            return;
        } // Run


    } // class
}

FunctionsStartup is not being called, causing function dependency resolution to fail.

We downloaded the sample project, put a break point on builder.Services.AddScoped<IGreeter, SampleGreeter>(); expecting it to be called when the runtime started and discovered functions. Unfortunately it did no, so we attempted to invoke the function directly to see if the runtime would call the FunctionStartup class upon first function invocation. Unfortunately it did not and both times resulted in:

Executed 'SampleFunction' (Failed, Id=eeaabc43-d8a6-4815-9fe2-0834f7d4c47b)
[5/8/2019 9:58:22 PM] Microsoft.Extensions.DependencyInjection.Abstractions: Unable to resolve service for type 'Microsoft.Azure.Functions.Samples.DependencyInjectionBasic.IGreeter' while attempting to activate 'Microsoft.Azure.Functions.Samples.DependencyInjectionBasic.SampleFunction'.

Is there something we are missing? It does not appear that the FunctionsStartup method is actually being called by the runtime.

[Question] How to use appsetting.json values in a trigger?

I knew we can use appsettings.json in azure function, but I don't know how can I make the trigger read the values from this file.

simply, I want the trigger to read from appsettings.development.json instead of local.settings.json because I keep switching between WebApp and Azure Function.

so I want to do this

[CosmosDbTrigger(ConnectionStringSetting = "this values should come from appsettings.development.json" ... ]

DI sample code works when Function App is v2 but not v3

I cannot get dependency injection to work in Azure Functions (documentation here) using a v3 Function App with .NET Core 3.1. (it will work locally but fails when deployed to Azure) The exact same code does work when deployed to a v2 Function App with .NET Core 2.1. The test code is forked from a sample maintained by a docs.microsoft.com contributor.

@fabiocav I apologize for how long these steps are, but I wanted to be sure the report was reproducible. Am I doing something wrong, or should I fallback to v2 for the next few weeks?

Create a function app instance

Log in to my subscription and create a new Function App

Basics

image

  • Create new resource group fa-rg
  • Name function app di-in-azure-func

Note: even though I want to initially run this on .NET Core 2.1 to verify the sample code works, the only choice provided while doing initial setup is 3.1. We will adjust the runtime version after the function app instance is deployed.

Click “Next: Hosting”

Hosting

image

  • Create a new storage account diinazurefuncstore.
  • Change Plan type to App service plan. Create new plan called di-in-azure-func-plan.
  • Change Plan sku and size to B1. (free option does not allow setting bitness of function app)

Click “Next: Monitoring”

Monitoring

image

  • Create a new App Insights di-in-azure-func-ai.

Click “Review + create”

Review + Create

image

Click “Create”. Wait for the deployment to finish. Once the deployment finishes, choose “Go to resource”.

image

Configure the function app instance for .NET Core 2

We need to adjust several settings for the sample code to run properly.

Set runtime version

Choose “Function app settings”. Note the runtime version is set to 3. Click 2. Wait patiently.

image

Set bitness and always on

Go to Configuration. Choose the General settings tab.

image

  • Change Platform to 64bit. (we are compiling to 64bit)
  • Change Always On to On. (troubleshooting convenience, prevent app from going to sleep)
  • Choose “Save”. Confirm restarting is OK by choosing “Continue”.

Deploy the sample code with .NET Core 2

I forked the official sample from https://github.com/mike-urnun-msft/AzureFunkDI to https://github.com/nolanegly/AzureFunkDI in order to upgrade the .NET Core version and demonstrate the problem. I checked out the code to c:\dev\ resulting in a solution location of c:\dev\AzureFunkDI.

Build

On the master branch, with no code changes to the sample, publish the project. If the output directory c:\dev\stage already exists, delete it first. In a PowerShell prompt, navigate to the directory of the project and do dotnet publish --configuration “Release” --self-contained -r “win-x64” --output “c:\dev\stage”

image

Compress

After building the project, compress the output into a single zip for deployment. If the file c:\dev\stage\funkdi.zip exists, delete it first. In a PowerShell prompt, do `Compress-Archive /dev/stage/* -DestinationPath “c:\dev\funkdi.zip”

image

Deploy to Azure

To deploy the zip you must have installed the Azure CLI, available here if you don’t already have it.

If needed, log in to Azure CLI by typing az login in PowerShell.

Deploy the zipped payload to the function app by typing az functionapp deployment source config-zip -g fa-rg -n di-in-azure-func --src c:\dev\funkdi.zip

  • If you’ve made a different resource group name, app function name, or zip file location/name, substitute those values.

image

Verify the sample code works in v2

Navigate to the function app. On the left side, select “HttpTrigger”. Wait patiently. On the right side, select the “Test” tab.

  • Change the HTTP method to GET.
  • Under Query, Choose “Add parameter”. Use “name” and “demo”.
  • Choose “Run” button at the bottom of the Test panel (you may have to scroll down to see it).

In the bottom of the Test panel, the Output pane will say “Hello demo!” with a Status of “200 OK”. There will be no errors in the Logs pane.

image

Adjust code to .NET Core 3

On your local development machine, change branches from “master” to “upgrade-to-core-31” (again, this on the repository https://github.com/nolanegly/AzureFunkDI)

Observe the only changes are setting the project to .NET Core 3, Function App version 3, and the corresponding SDK dll to 3.0.5.

image

Deploy the sample code with .NET Core 3

Delete the previously built c:\dev\funkdi.zip file and c:\dev\stage directory.
Publish the project with dotnet publish … as done previously.
Compress the project with Compress-Archive … as done previously.
Deploy the package with az functionapp … as done previously.

Configure the function app instance for .NET Core 3

In the portal, go to the “Function app settings”. Change the Runtime version to 3. Wait patiently.

image

Observe the sample code fails in v3

Navigate to the function app. On the left side, select “HttpTrigger”. Wait patiently. On the right side, select the “Test” tab.

  • Change the HTTP method to GET.
  • Under Query, Choose “Add parameter”. Use “name” and “demo”.
  • Choose “Run” button at the bottom of the Test panel (you may have to scroll down to see it).

EXPECTED

The same results we got in the section “Verify the sample code works in v2”

ACTUAL

In the bottom of the Test panel, the Output pane will have a Status of “500 Internal Server Error”. There will be a dependency injection failure in the error log.

System.InvalidOperationException : Unable to resolve service for type 'AzureFunkDI.IGreeter' while attempting to activate 'AzureFunkDI.HttpTrigger'. 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 : 37 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 : 846
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 : 117
`

image

Support for other DI containers, e.g. AutoFac

My functions app is part of a wider solution that already uses Autofac for dependency injection … and was using Autofac DI through one of the earlier workarounds.

How would I set about using Autofac from the new supported DI structure? Other places that use Microsoft.Extensions.DependencyInjection.Abstractions seems to support switching the DI container.

Url is missing from appinsights logs for requests if use FunctionStartup

  1. Run any number of load on sandbox
  2. Go to appinsights -> Logs
  3. Query for the following -
    requests | where cloud_RoleName contains "test" | order by duration desc | project itemType, cloud_RoleName, url, appName, timestamp, name, cloud_RoleInstance.

What we have observed - If Startup class inherit IWebJobStartup then we are getting URL in appinsights logs for request, but if Startup class inherit FunctionStartup then we are not getting Url in appinsights logs.

We want to use Startup class Inherit FunctionStartup as we have written so much code based upon that in so many services. And we want to use constructor DI which is not possible in IWebJobStartup (as per sample which I have).

URL_Missing_AppInsights

  1. Getting URL in appinsight logs if we use below code in startup class

[assembly: WebJobsStartup(typeof(Startup))]
namespace TestApplicationWebJob.Infrastructure
{
[ExcludeFromCodeCoverage]
internal class Startup : IWebJobsStartup
{
static string appInstanceId = Guid.NewGuid().ToString();
public void Configure(IWebJobsBuilder builder)
{
#pragma warning disable CS0618 // Type or member is obsolete
builder.AddDependencyInjection(ConfigureServices);
builder.AddSwashBuckle(Assembly.GetExecutingAssembly(), opts =>
{

  1. Not getting URL in appinsights logs, if we use below code in startup class

[assembly: FunctionsStartup(typeof(Startup))]
namespace TestApplicationFunc.Infrastructure
{
[ExcludeFromCodeCoverage]
public class Startup : FunctionsStartup
{
public override void Configure(IFunctionsHostBuilder builder)
{
RegisterServices(builder.Services);

        builder.AddSwashBuckle(Assembly.GetExecutingAssembly(), opts =>
        {
            opts.SpecVersion = OpenApiSpecVersion.OpenApi3_0;
            opts.Documents = new[]
            {
                new SwaggerDocument
                {

Get ExecutionContext.InvocationId in startup (Azure function V2)

Currently I can retrieve ExecutionContext inside the function method, like this:
public async Task <IActionResult> Run ([HttpTrigger (AuthorizationLevel.Anonymous, "post", Route = null)], ILogger log, ExecutionContext context)

Is there any way I can retrieve ExecutionContext from my function startup?

Problem with referencing one scoped service in another

I have a Entity framework DatabaseContext that I like to add also as my DatabaseContextBase.
DatabaseContext inherits from DatabaseContextBase and DatabaseContextBase inherits from DbContext.

Here is how I've tried it:

In startup:

 services.AddDbContext<DatabaseContext>(options =>...);
services.AddScoped<DatabaseContextBase, DatabaseContext>(sp => sp.GetRequiredService<DatabaseContext>());
services.AddScoped<SomethingThatUsesDatabaseContext>();
services.AddScoped<SomethingThatUsesDatabaseContextBase>();

Then in the function I use those 2:

SomethingThatUsesDatabaseContext.DoSomething();
SomethingThatUsesDatabaseContextBase.DoSomethingElse();

The first one works fine but the second one fails with this exception:

System.ObjectDisposedException
HResult=0x80131622
Message=Cannot access a disposed object. A common cause of this error is disposing a context that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur if you are calling Dispose() on the context, or wrapping the context in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context instances.
Object name: 'DatabaseContext'.
Source=Microsoft.EntityFrameworkCore
StackTrace:
at Microsoft.EntityFrameworkCore.DbContext.CheckDisposed()
at Microsoft.EntityFrameworkCore.DbContext.AddRangeAsync(Object[] entities)
at Microsoft.EntityFrameworkCore.Internal.InternalDbSet`1.AddRangeAsync(TEntity[] entities)
at SomethingThatUsesDatabaseContextBase
.d__6.MoveNext() in

Scoped Services Instantiated Multiple Times on Single Function Run

When registering a scoped service with an implementationFactory set, multiple instances of the service are being created per run of a function. To recreate this issue, I used the following Startup in a sample project:

using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
using Services;
using System;
using System.Collections.Generic;
using System.Text;

[assembly: FunctionsStartup(typeof(CakeOrdersFunctions.Startup))]
namespace CakeOrdersFunctions
{
    public class Startup : FunctionsStartup
    {
        public override void Configure(IFunctionsHostBuilder builder)
        {
            builder.Services.AddScoped<ISupplier, Supplier>();
            builder.Services.AddScoped<IStoreFront>(x => new StoreFront());
            builder.Services.AddScoped<IBakery, Bakery>();

            //Ingredients/registers added in the ISupplier/IStoreFront services will not be reflected in this service:
            builder.Services.AddScoped<IManualBakery>(x => new ManualBakery(x.GetRequiredService<ISupplier>(), x.GetRequiredService<IStoreFront>()));
        }
    }
}

Azure Function Code

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Extensions.Logging;
using Services;
using System.Threading.Tasks;

namespace CakeOrdersFunctions
{
    public class SetupBakery
    {
        public readonly IStoreFront _storeFront;
        public readonly ISupplier _supplier;
        public readonly IBakery _bakery;
        public readonly IManualBakery _manualBakery;

        public SetupBakery(IStoreFront storeFront,
            ISupplier supplier,
            IBakery bakery,
            IManualBakery manualBakery)
        {
            _storeFront = storeFront;
            _supplier = supplier;
            _bakery = bakery;
            _manualBakery = manualBakery;
        }

        [FunctionName("SetupBakery")]
        public async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            _storeFront.AddRegister("emp1");
            _storeFront.AddRegister("emp2");

            _supplier.AddIngredient("sugar");
            _supplier.AddIngredient("love");

            var stats = new
            {
                StoreFrontRegisters = _storeFront.GetAvailableRegisters(),
                SupplierIngedients = _supplier.GetIngredientCount(),
                BakerRegisters = _bakery.GetAvailableRegisters(),
                BakeryIngredients = _bakery.GetSupplierIngredientCount(),
                ManualBakeryRegisters = _manualBakery.GetAvailableRegisters(),
                ManualBakeryIngredients = _manualBakery.GetSupplierIngredientCount()
            };

            return new OkObjectResult(stats);
        }
    }
}

Services:

public class Bakery : IBakery
    {
        private readonly ISupplier _supplier;
        private readonly IStoreFront _storeFront;

        public Bakery(ISupplier supplier, IStoreFront storeFront)
        {
            _supplier = supplier;
            _storeFront = storeFront;
        }

        public void BakeCake()
        {

        }

        public int GetSupplierIngredientCount() => _supplier.GetIngredientCount();
        public int GetAvailableRegisters() => _storeFront.GetAvailableRegisters();
    }

private readonly ISupplier _supplier;
        private readonly IStoreFront _storeFront;

        public ManualBakery(ISupplier supplier, IStoreFront storeFront)
        {
            _supplier = supplier;
            _storeFront = storeFront;
        }

        public void BakeCake()
        {

        }

        public int GetSupplierIngredientCount() => _supplier.GetIngredientCount();
        public int GetAvailableRegisters() => _storeFront.GetAvailableRegisters();

public class StoreFront : IStoreFront
    {
        private ICollection<string> _registers;

        public StoreFront()
        {
            _registers = new List<string>();
        }

        public void AddRegister(string employee)
        {
            _registers.Add(employee);
        }

        public int GetAvailableRegisters() => _registers.Count();
    }

public class Supplier : ISupplier
    {
        private ICollection<string> _availableIngredients;

        public Supplier()
        {
            _availableIngredients = new List<String>();
        }

        public void AddIngredient(string ingredient)
        {
            _availableIngredients.Add(ingredient);
        }

        public int GetIngredientCount() => _availableIngredients.Count();
    }

Results (all values should be 2):

{
    "storeFrontRegisters": 2,
    "supplierIngedients": 2,
    
//builder.Services.AddScoped<IBakery, Bakery>();
    "bakeryRegisters": 2,
    "bakeryIngredients": 2,
	
//builder.Services.AddScoped<IManualBakery>(x => new ManualBakery(x.GetRequiredService<ISupplier>(), x.GetRequiredService<IStoreFront>()));
    "manualBakeryRegisters": 0,
    "manualBakeryIngredients": 0
}

I also replicated the service registration in an ASP.NET Core project to verify that this is an Azure Functions-specific issue.

When will 1.1.0 final be released?

Really looking forward to being able to use the new features - how long is it necessary to keep these in preview, considering that the requisite runtime versions have long been rolled out to all Azure customers?

get_Services method not found

I am trying to add DI to our existing azure functions(.Net Core 2.0). Followed the steps mentioned in this link - https://docs.microsoft.com/en-us/azure/azure-functions/functions-dotnet-dependency-injection

However, I am getting the following error. Are there any other packages that I need to install or update?

System.MissingMethodException: Method not found: 'Microsoft.Extensions.DependencyInjection.IServiceCollection Microsoft.Azure.WebJobs.IWebJobsBuilder.get_Services()'

Value cannot be null.
Parameter name: provider

Appreciate any help.

Thanks!

DependencyInjection stops working when we add User Secrets (Error: "Microsoft.Extensions.DependencyInjection.Abstractions: Unable to resolve [injected service] while attempting to activate [function])

I know this issue was already discussed here: #45, but the issue should not have been closed. The person in that thread mentioned that they solved their problem by simply installing Microsoft.Extensions.Configuration.UserSecrets, but I personally have that package installed. As soon as I installed it, my Dependency Injection stopped working.

I created a very basic Functions app to show the problem. The function only has three installed packages. The csproj file is:

image

The Startup.cs file:

image

And the very simple function:

image

When I run the application (locally) I get the following error message:

image

Obviously, the error disappears if I remove the User Secrets package, but I need to be able to use User Secrets... There has to be a solution?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.