Skip to content

Commit

Permalink
Fix local telemetry client dependency (#26)
Browse files Browse the repository at this point in the history
* Fix local telemetry client dependency
* Bump sample to NET 6
* Add dotnet 6 build process
  • Loading branch information
junalmeida authored May 19, 2022
1 parent cf2cb77 commit 640bcee
Show file tree
Hide file tree
Showing 12 changed files with 225 additions and 18 deletions.
6 changes: 5 additions & 1 deletion .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,10 @@ jobs:
steps:
- name: Checkout
uses: actions/checkout@v2

- uses: actions/setup-dotnet@v2
with:
dotnet-version: '6.0.x'

- name: "Get Commit Date"
uses: actions/[email protected]
Expand Down Expand Up @@ -53,7 +57,7 @@ jobs:
run: nuget restore

- name: Build
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
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

- uses: actions/upload-artifact@v2
name: Upload artifact
Expand Down
6 changes: 6 additions & 0 deletions .vscode/extensions.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"recommendations": [
"ms-azuretools.vscode-azurefunctions",
"ms-dotnettools.csharp"
]
}
14 changes: 14 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Attach to .NET Functions",
"type": "coreclr",
"request": "attach",
"processId": "${command:azureFunctions.pickProcess}"
}
]
}
7 changes: 7 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"azureFunctions.deploySubpath": "SampleAutofacFunction/bin/Release/netcoreapp3.1/publish",
"azureFunctions.projectLanguage": "C#",
"azureFunctions.projectRuntime": "~3",
"debug.internalConsoleOptions": "neverOpen",
"azureFunctions.preDeployTask": "publish (functions)"
}
81 changes: 81 additions & 0 deletions .vscode/tasks.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
{
"version": "2.0.0",
"tasks": [
{
"label": "clean (functions)",
"command": "dotnet",
"args": [
"clean",
"/property:GenerateFullPaths=true",
"/consoleloggerparameters:NoSummary"
],
"type": "process",
"problemMatcher": "$msCompile",
"options": {
"cwd": "${workspaceFolder}/SampleAutofacFunction"
}
},
{
"label": "build (functions)",
"command": "dotnet",
"args": [
"build",
"/property:GenerateFullPaths=true",
"/consoleloggerparameters:NoSummary"
],
"type": "process",
"dependsOn": "clean (functions)",
"group": {
"kind": "build",
"isDefault": true
},
"problemMatcher": "$msCompile",
"options": {
"cwd": "${workspaceFolder}/SampleAutofacFunction"
}
},
{
"label": "clean release (functions)",
"command": "dotnet",
"args": [
"clean",
"--configuration",
"Release",
"/property:GenerateFullPaths=true",
"/consoleloggerparameters:NoSummary"
],
"type": "process",
"problemMatcher": "$msCompile",
"options": {
"cwd": "${workspaceFolder}/SampleAutofacFunction"
}
},
{
"label": "publish (functions)",
"command": "dotnet",
"args": [
"publish",
"--configuration",
"Release",
"/property:GenerateFullPaths=true",
"/consoleloggerparameters:NoSummary"
],
"type": "process",
"dependsOn": "clean release (functions)",
"problemMatcher": "$msCompile",
"options": {
"cwd": "${workspaceFolder}/SampleAutofacFunction"
}
},
{
"type": "func",
"dependsOn": "build (functions)",
"options": {
"cwd": "${workspaceFolder}/SampleAutofacFunction/bin/Debug/netcoreapp3.1"
},
"command": "host start",
"isBackground": true,
"problemMatcher": "$func-dotnet-watch"
}
]
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
<TargetFramework>netstandard2.0</TargetFramework>
<VersionPrefix>6.0.0</VersionPrefix>
<Description>Autofac implementation of the dependency injection factory for Azure Functions.</Description>
<Copyright>Copyright © 2020 Marcos Almeida Jr</Copyright>
<Copyright>Copyright © 2022 Marcos Almeida Jr</Copyright>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<NeutralResourcesLanguage>en-US</NeutralResourcesLanguage>
Expand All @@ -26,11 +26,11 @@
<Product>Autofac</Product>
<IsPackable>true</IsPackable>
<PackageOutputPath>$(OutDir)/$(AssemblyName)</PackageOutputPath>
<PackageVersion>6.0.0</PackageVersion>
<PackageVersion>7.2.0</PackageVersion>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Autofac.Extensions.DependencyInjection" Version="7.1.0" />
<PackageReference Include="Autofac.Extensions.DependencyInjection" Version="7.2.0" />
<PackageReference Include="Microsoft.Azure.Functions.Extensions" Version="1.1.0" />
</ItemGroup>

Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.Azure.WebJobs.Host.Executors;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using System;
using System.Linq;

namespace Autofac.Extensions.DependencyInjection.AzureFunctions
{
Expand All @@ -11,6 +13,10 @@ namespace Autofac.Extensions.DependencyInjection.AzureFunctions
/// </summary>
public static class ConfigurationExtensions
{
internal const string functionInstanceParam = "functionInstance";
internal const string iEnvironmentParam = "iEnvironment";

internal static Type IEnvironmentType;
/// <summary>
/// Attatch the <see cref="AutofacServiceProvider"/> to the <see cref="IFunctionsHostBuilder"/> of the current function host.
/// </summary>
Expand All @@ -31,6 +37,27 @@ public static IFunctionsHostBuilder UseAutofacServiceProviderFactory(this IFunct
// Call the user code to configure the container
configurationAction?.Invoke(containerBuilder);
IEnvironmentType = hostBuilder.Services.Where(s => s.ServiceType.Namespace == "Microsoft.Azure.WebJobs.Script").FirstOrDefault()?.ServiceType.Assembly.GetExportedTypes().Where(x => x.Name == "IEnvironment").FirstOrDefault();
if (IEnvironmentType != null)
{
containerBuilder.Register((r, p) =>
{
var instance = p.Named<object>(iEnvironmentParam);
return instance;
}).As(IEnvironmentType)
.ExternallyOwned()
.SingleInstance();
}
containerBuilder.Register((r, p) =>
{
var instance = p.Named<IFunctionInstanceEx>(functionInstanceParam);
return instance;
})
.AsSelf()
.ExternallyOwned()
.InstancePerTriggerRequest();
var container = containerBuilder.Build();
return new AutofacContainer(container);
});
Expand Down Expand Up @@ -66,7 +93,7 @@ internal class ScopedContainer : IDisposable
public ILifetimeScope Scope { get; }
public ScopedContainer(AutofacContainer container)
{
Scope = container.Container.BeginLifetimeScope(Scopes.RootLifetimeScopeTag);
Scope = container.Container.BeginLifetimeScope(Scopes.LifetimeScopeTag);
}

public void Dispose()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ internal class LoggerModule : Module
public const string functionNameParam = "functionName";
public const string loggerFactoryParam = "loggerFactory";


protected override void Load(ContainerBuilder builder)
{
builder
Expand All @@ -17,6 +18,7 @@ protected override void Load(ContainerBuilder builder)
return factory;
})
.AsSelf()
.ExternallyOwned()
.SingleInstance();

builder
Expand All @@ -30,6 +32,7 @@ protected override void Load(ContainerBuilder builder)
.AsSelf()
.InstancePerTriggerRequest();


}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Diagnostics;

namespace Autofac.Extensions.DependencyInjection.AzureFunctions
{
Expand All @@ -25,10 +26,9 @@ public T CreateInstance<T>()
public T CreateInstance<T>(IFunctionInstanceEx functionInstance)
{
var scope = functionInstance.InstanceServices.GetService<ScopedContainer>()?.Scope ?? _serviceProvider.GetRequiredService<ScopedContainer>()?.Scope;

// Some dependencies of ILoggerFactory are registered after
// FunctionsStartup, thus not allowing us to get the
// ILoggerFactory from Autofac container.
// FunctionsStartup, on a separate ServicesCollection, thus
// not allowing us to get the ILoggerFactory from Autofac container.
// So we are retrieving it from InstanceServices.
var loggerFactory = functionInstance.InstanceServices.GetService<ILoggerFactory>() ?? scope.Resolve<ILoggerFactory>();
scope.Resolve<ILoggerFactory>(
Expand All @@ -43,6 +43,26 @@ public T CreateInstance<T>(IFunctionInstanceEx functionInstance)
new NamedParameter(LoggerModule.functionNameParam, functionName)
);

// Add the functionInstanceEx itself to the scope
scope.Resolve<IFunctionInstanceEx>(
new NamedParameter(ConfigurationExtensions.functionInstanceParam, functionInstance)
);
if (ConfigurationExtensions.IEnvironmentType != null) // Required for TelemetryClient
{
var iEnvironment = functionInstance.InstanceServices.GetService(ConfigurationExtensions.IEnvironmentType);
scope.Resolve(ConfigurationExtensions.IEnvironmentType, new NamedParameter(ConfigurationExtensions.iEnvironmentParam, iEnvironment));
}
if (Activity.Current == null)
{
var activity = new Activity(functionName);
Activity.Current = activity.Start();

scope.CurrentScopeEnding += (sender, e) =>
{
activity.Stop();
};
}

return CreateInstance<T>(scope);
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
using Autofac.Builder;
using System;
using System;
using System.Linq;
using Autofac.Builder;

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

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

var tags = new[] { Scopes.RootLifetimeScopeTag }.Concat(lifetimeScopeTags).ToArray();
var tags = new[] { Scopes.LifetimeScopeTag }.Concat(lifetimeScopeTags).ToArray();
return registration.InstancePerMatchingLifetimeScope(tags);
}

Expand Down
41 changes: 41 additions & 0 deletions SampleAutofacFunction/Functions/Function3.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
using Microsoft.Azure.WebJobs;
using Microsoft.Extensions.Logging;
using SampleAutofacFunction.Services;
using System;
using System.Diagnostics;
using System.Threading.Tasks;

namespace SampleAutofacFunction.Functions
{
public class Function3 : IDisposable
{
private readonly IService1 _service1;
private readonly ILogger _logger;
private readonly Guid _id = Guid.NewGuid();

public Function3(IService1 service1, ILogger logger)
{
_service1 = service1;
_logger = logger;
_logger.LogWarning($"Creating {this}");
}

public void Dispose()
{
_logger.LogWarning($"Disposing {this}");
}

[FunctionName(nameof(Function3))]
public async Task Run([TimerTrigger("0 */5 * * * *", RunOnStartup = true)] TimerInfo timer)
{
await Task.Delay(2000);
Activity.Current.AddTag("Test", "Hello World");
_logger.LogInformation($"C# Timer trigger function processed.");
}

public override string ToString()
{
return $"{_id} ({nameof(Function1)})";
}
}
}
16 changes: 10 additions & 6 deletions SampleAutofacFunction/SampleAutofacFunction.csproj
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
<AzureFunctionsVersion>v3</AzureFunctionsVersion>
<TargetFramework>net6.0</TargetFramework>
<AzureFunctionsVersion>v4</AzureFunctionsVersion>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.ApplicationInsights" Version="2.17.0" />
<PackageReference Include="Microsoft.Azure.WebJobs.Extensions.Storage" Version="4.0.4" />
<PackageReference Include="Microsoft.Azure.WebJobs.Logging.ApplicationInsights" Version="3.0.27" />
<PackageReference Include="Microsoft.NET.Sdk.Functions" Version="3.0.11" />
<PackageReference Include="Microsoft.ApplicationInsights" Version="2.20.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Abstractions" Version="2.2.0" />
<PackageReference Include="Microsoft.Azure.WebJobs.Extensions" Version="4.0.1" />
<PackageReference Include="Microsoft.Azure.WebJobs.Extensions.Http" Version="3.0.12" />
<PackageReference Include="Microsoft.Azure.WebJobs.Extensions.Storage" Version="5.0.1" />
<PackageReference Include="Microsoft.Azure.WebJobs.Extensions.Storage.Queues" Version="5.0.1" />
<PackageReference Include="Microsoft.Azure.WebJobs.Logging.ApplicationInsights" Version="3.0.33" />
<PackageReference Include="Microsoft.NET.Sdk.Functions" Version="4.1.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Autofac.Extensions.DependencyInjection.AzureFunctions\Autofac.Extensions.DependencyInjection.AzureFunctions.csproj" />
Expand Down

0 comments on commit 640bcee

Please sign in to comment.