Skip to content

Commit e76a929

Browse files
authored
Load post registered services (#15)
* Add post-registered services like TelemetryClient to Autofac. Fixes #10 * Fix empty PACKAGE_VERSION in devops.
1 parent 28f5a33 commit e76a929

File tree

6 files changed

+71
-24
lines changed

6 files changed

+71
-24
lines changed

.github/workflows/main.yml

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,8 @@ jobs:
1919
build:
2020
name: "Build"
2121
runs-on: "ubuntu-latest"
22-
22+
outputs:
23+
PACKAGE_VERSION: ${{ steps.version-number.outputs.PACKAGE_VERSION }}
2324
steps:
2425
- name: Checkout
2526
uses: actions/checkout@v2
@@ -34,10 +35,12 @@ jobs:
3435
return commit_details.data.author.date
3536
3637
- name: "Set Version Number"
38+
id: version-number
3739
run: |
3840
echo "VERSION_NUMBER=$(date -d ${{ steps.author-date.outputs.result }} +%Y.%m.%d.%H%M)" >> $GITHUB_ENV
3941
PACKAGE_VERSION=$(cat "$PACKAGE_PROJECT" | grep -oPm1 "(?<=<PackageVersion>)[^<]+")
4042
echo "PACKAGE_VERSION=$PACKAGE_VERSION.${{ github.run_number }}" >> $GITHUB_ENV
43+
echo "::set-output name=PACKAGE_VERSION::$PACKAGE_VERSION.${{ github.run_number }}"
4144
4245
- name: Setup NuGet
4346
uses: NuGet/setup-nuget@v1
@@ -64,7 +67,7 @@ jobs:
6467
if: ${{ github.ref == 'refs/heads/master' && !contains(github.event.push.commits.*.message, 'readme') }}
6568
environment:
6669
name: nuget
67-
url: https://www.nuget.org/packages/${{ env.NUGET_NAME }}/${{ env.PACKAGE_VERSION }}
70+
url: https://www.nuget.org/packages/${{ env.NUGET_NAME }}/${{ needs.build.outputs.PACKAGE_VERSION }}
6871

6972
steps:
7073
- uses: actions/download-artifact@v2
@@ -79,17 +82,17 @@ jobs:
7982
echo "Pushing $f...";
8083
nuget push "$f" -NonInteractive -Source "$NUGET_SOURCE" -ApiKey $NUGET_KEY;
8184
done;
82-
85+
8386
- name: Create Release
8487
id: create_release
8588
uses: actions/create-release@latest
8689
env:
8790
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # This token is provided by Actions, you do not need to create your own token
8891
with:
89-
tag_name: "v${{ env.PACKAGE_VERSION }}"
90-
release_name: ${{ env.PACKAGE_VERSION }}
92+
tag_name: "v${{ needs.build.outputs.PACKAGE_VERSION }}"
93+
release_name: ${{ needs.build.outputs.PACKAGE_VERSION }}
9194
body: |
92-
Changes in this [Release](https://www.nuget.org/packages/${{ env.NUGET_NAME }}/${{ env.PACKAGE_VERSION }})
95+
Changes in this [Release](https://www.nuget.org/packages/${{ env.NUGET_NAME }}/${{ needs.build.outputs.PACKAGE_VERSION }})
9396
${{ github.event.head_commit.message }}
9497
draft: false
9598
prerelease: false

Autofac.Extensions.DependencyInjection.AzureFunctions/ConfigurationExtensions.cs

Lines changed: 44 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -19,30 +19,59 @@ public static class ConfigurationExtensions
1919
/// <returns>The IFunctionsHostBuilder.</returns>
2020
public static IFunctionsHostBuilder UseAutofacServiceProviderFactory(this IFunctionsHostBuilder hostBuilder, Action<ContainerBuilder> configurationAction = null)
2121
{
22-
var containerBuilder = new ContainerBuilder();
23-
containerBuilder.Populate(hostBuilder.Services);
24-
containerBuilder.RegisterModule<LoggerModule>();
22+
// Adding as a Singleton service will make sure post-registered
23+
// services like TelemetryClient will be in the scope.
24+
hostBuilder.Services.AddSingleton((ctx) =>
25+
{
26+
var containerBuilder = new ContainerBuilder();
2527

26-
// Call the user code to configure the container
27-
configurationAction?.Invoke(containerBuilder);
28+
containerBuilder.Populate(hostBuilder.Services);
29+
containerBuilder.RegisterModule<LoggerModule>();
2830

29-
var container = containerBuilder.Build();
31+
// Call the user code to configure the container
32+
configurationAction?.Invoke(containerBuilder);
3033

31-
var scoped = new ScopedJobActivator(new AutofacServiceProvider(container));
34+
var container = containerBuilder.Build();
35+
return new AutofacContainer(container);
36+
});
3237

3338
// Replacing Azure Functions ServiceProvider
34-
hostBuilder.Services.Replace(ServiceDescriptor.Singleton(typeof(IJobActivator), scoped));
35-
hostBuilder.Services.Replace(ServiceDescriptor.Singleton(typeof(IJobActivatorEx), scoped));
39+
hostBuilder.Services.Replace(ServiceDescriptor.Singleton(typeof(IJobActivator), typeof(ScopedJobActivator)));
40+
hostBuilder.Services.Replace(ServiceDescriptor.Singleton(typeof(IJobActivatorEx), typeof(ScopedJobActivator)));
3641

3742
// This will create a scoped execution when a function is triggered.
38-
hostBuilder.Services.AddScoped((provider) =>
39-
{
40-
var lifetimeScope = container.BeginLifetimeScope(Scopes.RootLifetimeScopeTag);
41-
42-
return lifetimeScope;
43-
});
43+
hostBuilder.Services.AddScoped<ScopedContainer>();
4444

4545
return hostBuilder;
4646
}
4747
}
48+
49+
internal class AutofacContainer : IDisposable
50+
{
51+
public IContainer Container { get; }
52+
53+
public AutofacContainer(IContainer container)
54+
{
55+
Container = container;
56+
}
57+
58+
public void Dispose()
59+
{
60+
Container.Dispose();
61+
}
62+
}
63+
64+
internal class ScopedContainer : IDisposable
65+
{
66+
public ILifetimeScope Scope { get; }
67+
public ScopedContainer(AutofacContainer container)
68+
{
69+
Scope = container.Container.BeginLifetimeScope(Scopes.RootLifetimeScopeTag);
70+
}
71+
72+
public void Dispose()
73+
{
74+
Scope.Dispose();
75+
}
76+
}
4877
}

Autofac.Extensions.DependencyInjection.AzureFunctions/ScopedJobActivator.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,14 +17,14 @@ public ScopedJobActivator(IServiceProvider serviceProvider)
1717

1818
public T CreateInstance<T>()
1919
{
20-
var scope = _serviceProvider.GetService<ILifetimeScope>();
20+
var scope = _serviceProvider.GetRequiredService<ScopedContainer>().Scope;
2121

2222
return CreateInstance<T>(scope);
2323
}
2424

2525
public T CreateInstance<T>(IFunctionInstanceEx functionInstance)
2626
{
27-
var scope = functionInstance.InstanceServices.GetService<ILifetimeScope>() ?? _serviceProvider.GetService<ILifetimeScope>();
27+
var scope = functionInstance.InstanceServices.GetService<ScopedContainer>()?.Scope ?? _serviceProvider.GetRequiredService<ScopedContainer>()?.Scope;
2828

2929
// Some dependencies of ILoggerFactory are registered after
3030
// FunctionsStartup, thus not allowing us to get the

SampleAutofacFunction/Functions/Function2.cs

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
using Microsoft.ApplicationInsights;
12
using Microsoft.AspNetCore.Http;
23
using Microsoft.AspNetCore.Mvc;
34
using Microsoft.Azure.WebJobs;
@@ -6,6 +7,7 @@
67
using SampleAutofacFunction.Services;
78
using SampleAutofacFunction.Settings;
89
using System;
10+
using System.Collections.Generic;
911
using System.Threading.Tasks;
1012

1113
namespace SampleAutofacFunction.Functions
@@ -15,13 +17,15 @@ public class Function2 : IDisposable
1517
private readonly IService1 _service1;
1618
private readonly MySettings _settings;
1719
private readonly ILogger _logger;
20+
private readonly TelemetryClient _client;
1821
private readonly Guid _id = Guid.NewGuid();
1922

20-
public Function2(IService1 service1, MySettings settings, ILogger logger)
23+
public Function2(IService1 service1, MySettings settings, ILogger logger, TelemetryClient client)
2124
{
2225
_service1 = service1;
2326
_settings = settings;
2427
_logger = logger;
28+
_client = client;
2529
_logger.LogWarning($"Creating {this}");
2630
}
2731

@@ -46,6 +50,14 @@ This HTTP triggered function executed successfully.
4650
UrlRequested: {req.Path}
4751
";
4852

53+
_client.TrackEvent("HTTP Function Event", new Dictionary<string, string>() {
54+
{ "Injected Service Value", value },
55+
{ "MySettings Value1", _settings.Value1 },
56+
{ "MySettings Value2", _settings.Value2 },
57+
{ "UrlRequested", req.Path}
58+
});
59+
60+
4961
await Task.Delay(1000);
5062
_logger.LogInformation(responseMessage);
5163
return new OkObjectResult(responseMessage);

SampleAutofacFunction/SampleAutofacFunction.csproj

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,9 @@
44
<AzureFunctionsVersion>v3</AzureFunctionsVersion>
55
</PropertyGroup>
66
<ItemGroup>
7+
<PackageReference Include="Microsoft.ApplicationInsights" Version="2.17.0" />
78
<PackageReference Include="Microsoft.Azure.WebJobs.Extensions.Storage" Version="4.0.4" />
9+
<PackageReference Include="Microsoft.Azure.WebJobs.Logging.ApplicationInsights" Version="3.0.27" />
810
<PackageReference Include="Microsoft.NET.Sdk.Functions" Version="3.0.11" />
911
</ItemGroup>
1012
<ItemGroup>

SampleAutofacFunction/Startup.cs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ public override void Configure(IFunctionsHostBuilder builder)
2222
private void ConfigureLogger(ILoggingBuilder builder, IConfiguration config)
2323
{
2424
builder.AddConfiguration(config.GetSection("Logging"));
25+
builder.AddApplicationInsightsWebJobs();
2526
}
2627

2728
private void ConfigureContainer(ContainerBuilder builder)

0 commit comments

Comments
 (0)