Skip to content

Commit 640bcee

Browse files
authored
Fix local telemetry client dependency (#26)
* Fix local telemetry client dependency * Bump sample to NET 6 * Add dotnet 6 build process
1 parent cf2cb77 commit 640bcee

File tree

12 files changed

+225
-18
lines changed

12 files changed

+225
-18
lines changed

.github/workflows/main.yml

+5-1
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,10 @@ jobs:
2424
steps:
2525
- name: Checkout
2626
uses: actions/checkout@v2
27+
28+
- uses: actions/setup-dotnet@v2
29+
with:
30+
dotnet-version: '6.0.x'
2731

2832
- name: "Get Commit Date"
2933
uses: actions/github-script@0.3.0
@@ -53,7 +57,7 @@ jobs:
5357
run: nuget restore
5458

5559
- name: Build
56-
run: msbuild -p:Configuration="$BUILD_CONFIGURATION" -p:Platform="$BUILD_PLATFORM" -m -p:GeneratePackageOnBuild=true -p:OutDir=$PUBLISH_DIR -p:Version=$VERSION_NUMBER -p:AssemblyVersion=$VERSION_NUMBER -p:AssemblyInformationalVersion=$VERSION_NUMBER -p:PackageVersion=$PACKAGE_VERSION -p:GenerateProjectSpecificOutputFolder=true
60+
run: dotnet build -p:Configuration="$BUILD_CONFIGURATION" -p:Platform="$BUILD_PLATFORM" -m -p:GeneratePackageOnBuild=true -p:OutDir=$PUBLISH_DIR -p:Version=$VERSION_NUMBER -p:AssemblyVersion=$VERSION_NUMBER -p:AssemblyInformationalVersion=$VERSION_NUMBER -p:PackageVersion=$PACKAGE_VERSION -p:GenerateProjectSpecificOutputFolder=true
5761

5862
- uses: actions/upload-artifact@v2
5963
name: Upload artifact

.vscode/extensions.json

+6
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
{
2+
"recommendations": [
3+
"ms-azuretools.vscode-azurefunctions",
4+
"ms-dotnettools.csharp"
5+
]
6+
}

.vscode/launch.json

+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
{
2+
// Use IntelliSense to learn about possible attributes.
3+
// Hover to view descriptions of existing attributes.
4+
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
5+
"version": "0.2.0",
6+
"configurations": [
7+
{
8+
"name": "Attach to .NET Functions",
9+
"type": "coreclr",
10+
"request": "attach",
11+
"processId": "${command:azureFunctions.pickProcess}"
12+
}
13+
]
14+
}

.vscode/settings.json

+7
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
{
2+
"azureFunctions.deploySubpath": "SampleAutofacFunction/bin/Release/netcoreapp3.1/publish",
3+
"azureFunctions.projectLanguage": "C#",
4+
"azureFunctions.projectRuntime": "~3",
5+
"debug.internalConsoleOptions": "neverOpen",
6+
"azureFunctions.preDeployTask": "publish (functions)"
7+
}

.vscode/tasks.json

+81
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
{
2+
"version": "2.0.0",
3+
"tasks": [
4+
{
5+
"label": "clean (functions)",
6+
"command": "dotnet",
7+
"args": [
8+
"clean",
9+
"/property:GenerateFullPaths=true",
10+
"/consoleloggerparameters:NoSummary"
11+
],
12+
"type": "process",
13+
"problemMatcher": "$msCompile",
14+
"options": {
15+
"cwd": "${workspaceFolder}/SampleAutofacFunction"
16+
}
17+
},
18+
{
19+
"label": "build (functions)",
20+
"command": "dotnet",
21+
"args": [
22+
"build",
23+
"/property:GenerateFullPaths=true",
24+
"/consoleloggerparameters:NoSummary"
25+
],
26+
"type": "process",
27+
"dependsOn": "clean (functions)",
28+
"group": {
29+
"kind": "build",
30+
"isDefault": true
31+
},
32+
"problemMatcher": "$msCompile",
33+
"options": {
34+
"cwd": "${workspaceFolder}/SampleAutofacFunction"
35+
}
36+
},
37+
{
38+
"label": "clean release (functions)",
39+
"command": "dotnet",
40+
"args": [
41+
"clean",
42+
"--configuration",
43+
"Release",
44+
"/property:GenerateFullPaths=true",
45+
"/consoleloggerparameters:NoSummary"
46+
],
47+
"type": "process",
48+
"problemMatcher": "$msCompile",
49+
"options": {
50+
"cwd": "${workspaceFolder}/SampleAutofacFunction"
51+
}
52+
},
53+
{
54+
"label": "publish (functions)",
55+
"command": "dotnet",
56+
"args": [
57+
"publish",
58+
"--configuration",
59+
"Release",
60+
"/property:GenerateFullPaths=true",
61+
"/consoleloggerparameters:NoSummary"
62+
],
63+
"type": "process",
64+
"dependsOn": "clean release (functions)",
65+
"problemMatcher": "$msCompile",
66+
"options": {
67+
"cwd": "${workspaceFolder}/SampleAutofacFunction"
68+
}
69+
},
70+
{
71+
"type": "func",
72+
"dependsOn": "build (functions)",
73+
"options": {
74+
"cwd": "${workspaceFolder}/SampleAutofacFunction/bin/Debug/netcoreapp3.1"
75+
},
76+
"command": "host start",
77+
"isBackground": true,
78+
"problemMatcher": "$func-dotnet-watch"
79+
}
80+
]
81+
}

Autofac.Extensions.DependencyInjection.AzureFunctions/Autofac.Extensions.DependencyInjection.AzureFunctions.csproj

+3-3
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
<TargetFramework>netstandard2.0</TargetFramework>
55
<VersionPrefix>6.0.0</VersionPrefix>
66
<Description>Autofac implementation of the dependency injection factory for Azure Functions.</Description>
7-
<Copyright>Copyright © 2020 Marcos Almeida Jr</Copyright>
7+
<Copyright>Copyright © 2022 Marcos Almeida Jr</Copyright>
88
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
99
<GenerateDocumentationFile>true</GenerateDocumentationFile>
1010
<NeutralResourcesLanguage>en-US</NeutralResourcesLanguage>
@@ -26,11 +26,11 @@
2626
<Product>Autofac</Product>
2727
<IsPackable>true</IsPackable>
2828
<PackageOutputPath>$(OutDir)/$(AssemblyName)</PackageOutputPath>
29-
<PackageVersion>6.0.0</PackageVersion>
29+
<PackageVersion>7.2.0</PackageVersion>
3030
</PropertyGroup>
3131

3232
<ItemGroup>
33-
<PackageReference Include="Autofac.Extensions.DependencyInjection" Version="7.1.0" />
33+
<PackageReference Include="Autofac.Extensions.DependencyInjection" Version="7.2.0" />
3434
<PackageReference Include="Microsoft.Azure.Functions.Extensions" Version="1.1.0" />
3535
</ItemGroup>
3636

Autofac.Extensions.DependencyInjection.AzureFunctions/ConfigurationExtensions.cs

+28-1
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
11
using Microsoft.Azure.Functions.Extensions.DependencyInjection;
22
using Microsoft.Azure.WebJobs.Host;
3+
using Microsoft.Azure.WebJobs.Host.Executors;
34
using Microsoft.Extensions.DependencyInjection;
45
using Microsoft.Extensions.DependencyInjection.Extensions;
56
using System;
7+
using System.Linq;
68

79
namespace Autofac.Extensions.DependencyInjection.AzureFunctions
810
{
@@ -11,6 +13,10 @@ namespace Autofac.Extensions.DependencyInjection.AzureFunctions
1113
/// </summary>
1214
public static class ConfigurationExtensions
1315
{
16+
internal const string functionInstanceParam = "functionInstance";
17+
internal const string iEnvironmentParam = "iEnvironment";
18+
19+
internal static Type IEnvironmentType;
1420
/// <summary>
1521
/// Attatch the <see cref="AutofacServiceProvider"/> to the <see cref="IFunctionsHostBuilder"/> of the current function host.
1622
/// </summary>
@@ -31,6 +37,27 @@ public static IFunctionsHostBuilder UseAutofacServiceProviderFactory(this IFunct
3137
// Call the user code to configure the container
3238
configurationAction?.Invoke(containerBuilder);
3339

40+
IEnvironmentType = hostBuilder.Services.Where(s => s.ServiceType.Namespace == "Microsoft.Azure.WebJobs.Script").FirstOrDefault()?.ServiceType.Assembly.GetExportedTypes().Where(x => x.Name == "IEnvironment").FirstOrDefault();
41+
if (IEnvironmentType != null)
42+
{
43+
containerBuilder.Register((r, p) =>
44+
{
45+
var instance = p.Named<object>(iEnvironmentParam);
46+
return instance;
47+
}).As(IEnvironmentType)
48+
.ExternallyOwned()
49+
.SingleInstance();
50+
}
51+
52+
containerBuilder.Register((r, p) =>
53+
{
54+
var instance = p.Named<IFunctionInstanceEx>(functionInstanceParam);
55+
return instance;
56+
})
57+
.AsSelf()
58+
.ExternallyOwned()
59+
.InstancePerTriggerRequest();
60+
3461
var container = containerBuilder.Build();
3562
return new AutofacContainer(container);
3663
});
@@ -66,7 +93,7 @@ internal class ScopedContainer : IDisposable
6693
public ILifetimeScope Scope { get; }
6794
public ScopedContainer(AutofacContainer container)
6895
{
69-
Scope = container.Container.BeginLifetimeScope(Scopes.RootLifetimeScopeTag);
96+
Scope = container.Container.BeginLifetimeScope(Scopes.LifetimeScopeTag);
7097
}
7198

7299
public void Dispose()

Autofac.Extensions.DependencyInjection.AzureFunctions/LoggerModule.cs

+3
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ internal class LoggerModule : Module
77
public const string functionNameParam = "functionName";
88
public const string loggerFactoryParam = "loggerFactory";
99

10+
1011
protected override void Load(ContainerBuilder builder)
1112
{
1213
builder
@@ -17,6 +18,7 @@ protected override void Load(ContainerBuilder builder)
1718
return factory;
1819
})
1920
.AsSelf()
21+
.ExternallyOwned()
2022
.SingleInstance();
2123

2224
builder
@@ -30,6 +32,7 @@ protected override void Load(ContainerBuilder builder)
3032
.AsSelf()
3133
.InstancePerTriggerRequest();
3234

35+
3336
}
3437
}
3538
}

Autofac.Extensions.DependencyInjection.AzureFunctions/ScopedJobActivator.cs

+23-3
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
using Microsoft.Extensions.DependencyInjection;
44
using Microsoft.Extensions.Logging;
55
using System;
6+
using System.Diagnostics;
67

78
namespace Autofac.Extensions.DependencyInjection.AzureFunctions
89
{
@@ -25,10 +26,9 @@ public T CreateInstance<T>()
2526
public T CreateInstance<T>(IFunctionInstanceEx functionInstance)
2627
{
2728
var scope = functionInstance.InstanceServices.GetService<ScopedContainer>()?.Scope ?? _serviceProvider.GetRequiredService<ScopedContainer>()?.Scope;
28-
2929
// Some dependencies of ILoggerFactory are registered after
30-
// FunctionsStartup, thus not allowing us to get the
31-
// ILoggerFactory from Autofac container.
30+
// FunctionsStartup, on a separate ServicesCollection, thus
31+
// not allowing us to get the ILoggerFactory from Autofac container.
3232
// So we are retrieving it from InstanceServices.
3333
var loggerFactory = functionInstance.InstanceServices.GetService<ILoggerFactory>() ?? scope.Resolve<ILoggerFactory>();
3434
scope.Resolve<ILoggerFactory>(
@@ -43,6 +43,26 @@ public T CreateInstance<T>(IFunctionInstanceEx functionInstance)
4343
new NamedParameter(LoggerModule.functionNameParam, functionName)
4444
);
4545

46+
// Add the functionInstanceEx itself to the scope
47+
scope.Resolve<IFunctionInstanceEx>(
48+
new NamedParameter(ConfigurationExtensions.functionInstanceParam, functionInstance)
49+
);
50+
if (ConfigurationExtensions.IEnvironmentType != null) // Required for TelemetryClient
51+
{
52+
var iEnvironment = functionInstance.InstanceServices.GetService(ConfigurationExtensions.IEnvironmentType);
53+
scope.Resolve(ConfigurationExtensions.IEnvironmentType, new NamedParameter(ConfigurationExtensions.iEnvironmentParam, iEnvironment));
54+
}
55+
if (Activity.Current == null)
56+
{
57+
var activity = new Activity(functionName);
58+
Activity.Current = activity.Start();
59+
60+
scope.CurrentScopeEnding += (sender, e) =>
61+
{
62+
activity.Stop();
63+
};
64+
}
65+
4666
return CreateInstance<T>(scope);
4767
}
4868

Autofac.Extensions.DependencyInjection.AzureFunctions/Scopes.cs

+4-4
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
1-
using Autofac.Builder;
2-
using System;
1+
using System;
32
using System.Linq;
3+
using Autofac.Builder;
44

55
namespace Autofac.Extensions.DependencyInjection.AzureFunctions
66
{
@@ -12,7 +12,7 @@ public static class Scopes
1212
/// <summary>
1313
/// Represents the scope of a function trigger request.
1414
/// </summary>
15-
public const string RootLifetimeScopeTag = "AutofacFunctionsScope";
15+
public const string LifetimeScopeTag = "AutofacFunctionsScope";
1616

1717
/// <summary>
1818
/// Share one instance of the component within the context of a single
@@ -32,7 +32,7 @@ public static IRegistrationBuilder<TLimit, TActivatorData, TStyle> InstancePerTr
3232
if (registration == null)
3333
throw new ArgumentNullException(nameof(registration));
3434

35-
var tags = new[] { Scopes.RootLifetimeScopeTag }.Concat(lifetimeScopeTags).ToArray();
35+
var tags = new[] { Scopes.LifetimeScopeTag }.Concat(lifetimeScopeTags).ToArray();
3636
return registration.InstancePerMatchingLifetimeScope(tags);
3737
}
3838

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
using Microsoft.Azure.WebJobs;
2+
using Microsoft.Extensions.Logging;
3+
using SampleAutofacFunction.Services;
4+
using System;
5+
using System.Diagnostics;
6+
using System.Threading.Tasks;
7+
8+
namespace SampleAutofacFunction.Functions
9+
{
10+
public class Function3 : IDisposable
11+
{
12+
private readonly IService1 _service1;
13+
private readonly ILogger _logger;
14+
private readonly Guid _id = Guid.NewGuid();
15+
16+
public Function3(IService1 service1, ILogger logger)
17+
{
18+
_service1 = service1;
19+
_logger = logger;
20+
_logger.LogWarning($"Creating {this}");
21+
}
22+
23+
public void Dispose()
24+
{
25+
_logger.LogWarning($"Disposing {this}");
26+
}
27+
28+
[FunctionName(nameof(Function3))]
29+
public async Task Run([TimerTrigger("0 */5 * * * *", RunOnStartup = true)] TimerInfo timer)
30+
{
31+
await Task.Delay(2000);
32+
Activity.Current.AddTag("Test", "Hello World");
33+
_logger.LogInformation($"C# Timer trigger function processed.");
34+
}
35+
36+
public override string ToString()
37+
{
38+
return $"{_id} ({nameof(Function1)})";
39+
}
40+
}
41+
}

SampleAutofacFunction/SampleAutofacFunction.csproj

+10-6
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,17 @@
11
<Project Sdk="Microsoft.NET.Sdk">
22
<PropertyGroup>
3-
<TargetFramework>netcoreapp3.1</TargetFramework>
4-
<AzureFunctionsVersion>v3</AzureFunctionsVersion>
3+
<TargetFramework>net6.0</TargetFramework>
4+
<AzureFunctionsVersion>v4</AzureFunctionsVersion>
55
</PropertyGroup>
66
<ItemGroup>
7-
<PackageReference Include="Microsoft.ApplicationInsights" Version="2.17.0" />
8-
<PackageReference Include="Microsoft.Azure.WebJobs.Extensions.Storage" Version="4.0.4" />
9-
<PackageReference Include="Microsoft.Azure.WebJobs.Logging.ApplicationInsights" Version="3.0.27" />
10-
<PackageReference Include="Microsoft.NET.Sdk.Functions" Version="3.0.11" />
7+
<PackageReference Include="Microsoft.ApplicationInsights" Version="2.20.0" />
8+
<PackageReference Include="Microsoft.AspNetCore.Mvc.Abstractions" Version="2.2.0" />
9+
<PackageReference Include="Microsoft.Azure.WebJobs.Extensions" Version="4.0.1" />
10+
<PackageReference Include="Microsoft.Azure.WebJobs.Extensions.Http" Version="3.0.12" />
11+
<PackageReference Include="Microsoft.Azure.WebJobs.Extensions.Storage" Version="5.0.1" />
12+
<PackageReference Include="Microsoft.Azure.WebJobs.Extensions.Storage.Queues" Version="5.0.1" />
13+
<PackageReference Include="Microsoft.Azure.WebJobs.Logging.ApplicationInsights" Version="3.0.33" />
14+
<PackageReference Include="Microsoft.NET.Sdk.Functions" Version="4.1.0" />
1115
</ItemGroup>
1216
<ItemGroup>
1317
<ProjectReference Include="..\Autofac.Extensions.DependencyInjection.AzureFunctions\Autofac.Extensions.DependencyInjection.AzureFunctions.csproj" />

0 commit comments

Comments
 (0)