diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..3e759b7 --- /dev/null +++ b/.gitignore @@ -0,0 +1,330 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore + +# User-specific files +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUNIT +*.VisualState.xml +TestResult.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ +**/Properties/launchSettings.json + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_i.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# JustCode is a .NET coding add-in +.JustCode + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# JetBrains Rider +.idea/ +*.sln.iml + +# CodeRush +.cr/ + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ diff --git a/Microsoft.Azure.Functions.V2.DI.Testing.Service/ITestService.cs b/Microsoft.Azure.Functions.V2.DI.Testing.Service/ITestService.cs new file mode 100644 index 0000000..24af931 --- /dev/null +++ b/Microsoft.Azure.Functions.V2.DI.Testing.Service/ITestService.cs @@ -0,0 +1,7 @@ +namespace Microsoft.Azure.Functions.V2.DI.Testing.Service +{ + public interface ITestService + { + string GetResult(); + } +} diff --git a/Microsoft.Azure.Functions.V2.DI.Testing.Service/ITestServiceSingleInstance.cs b/Microsoft.Azure.Functions.V2.DI.Testing.Service/ITestServiceSingleInstance.cs new file mode 100644 index 0000000..dc0a698 --- /dev/null +++ b/Microsoft.Azure.Functions.V2.DI.Testing.Service/ITestServiceSingleInstance.cs @@ -0,0 +1,7 @@ +namespace Microsoft.Azure.Functions.V2.DI.Testing.Service +{ + public interface ITestServiceSingleInstance + { + string GetSingleValue(); + } +} \ No newline at end of file diff --git a/Microsoft.Azure.Functions.V2.DI.Testing.Service/Microsoft.Azure.Functions.V2.DI.Testing.Service.csproj b/Microsoft.Azure.Functions.V2.DI.Testing.Service/Microsoft.Azure.Functions.V2.DI.Testing.Service.csproj new file mode 100644 index 0000000..c630dd6 --- /dev/null +++ b/Microsoft.Azure.Functions.V2.DI.Testing.Service/Microsoft.Azure.Functions.V2.DI.Testing.Service.csproj @@ -0,0 +1,12 @@ + + + + netstandard2.0 + 7.2 + + + + + + + diff --git a/Microsoft.Azure.Functions.V2.DI.Testing.Service/TestService.cs b/Microsoft.Azure.Functions.V2.DI.Testing.Service/TestService.cs new file mode 100644 index 0000000..b6fa2f7 --- /dev/null +++ b/Microsoft.Azure.Functions.V2.DI.Testing.Service/TestService.cs @@ -0,0 +1,32 @@ +using System; + +namespace Microsoft.Azure.Functions.V2.DI.Testing.Service +{ + public class TestService : ITestService + { + private readonly IFunctionsContextResolver _contextResolver; + private readonly ITestServiceSingleInstance _testSingleInstance; + private readonly string _guidOnConstructor; + private readonly IMockResolver _mockResolver; + + public TestService( + IFunctionsContextResolver contextResolver, + ITestServiceSingleInstance testSingleInstance, + IMockResolver mockResolver) + { + _contextResolver = contextResolver; + _testSingleInstance = testSingleInstance; + _guidOnConstructor = Guid.NewGuid().ToString(); + _mockResolver = mockResolver; + } + + public string GetResult() + { + return + $"ScopedFunctionId: {_contextResolver.FunctionContext.FunctionInstanceId} " + Environment.NewLine + + $"TransientInstanceGuid: {_guidOnConstructor} " + Environment.NewLine + + $"SingleInstanceGuid: {_testSingleInstance.GetSingleValue()}" + Environment.NewLine + + $"IsMockEnabled: {_mockResolver.IsMockEnabled()}"; + } + } +} diff --git a/Microsoft.Azure.Functions.V2.DI.Testing.Service/TestServiceSingleInstance.cs b/Microsoft.Azure.Functions.V2.DI.Testing.Service/TestServiceSingleInstance.cs new file mode 100644 index 0000000..5ba0a51 --- /dev/null +++ b/Microsoft.Azure.Functions.V2.DI.Testing.Service/TestServiceSingleInstance.cs @@ -0,0 +1,14 @@ +using System; + +namespace Microsoft.Azure.Functions.V2.DI.Testing.Service +{ + public class TestServiceSingleInstance : ITestServiceSingleInstance + { + private readonly string _singleInstanceValue; + public TestServiceSingleInstance() + { + _singleInstanceValue = Guid.NewGuid().ToString(); + } + public string GetSingleValue() => _singleInstanceValue; + } +} \ No newline at end of file diff --git a/Microsoft.Azure.Functions.V2.DI.Testing/AzureFunctions/AzureFunctionV2.cs b/Microsoft.Azure.Functions.V2.DI.Testing/AzureFunctions/AzureFunctionV2.cs new file mode 100644 index 0000000..e3934c7 --- /dev/null +++ b/Microsoft.Azure.Functions.V2.DI.Testing/AzureFunctions/AzureFunctionV2.cs @@ -0,0 +1,21 @@ +using Microsoft.Azure.Functions.V2.DI.Testing.Service; +using Microsoft.Azure.WebJobs; +using Microsoft.Azure.WebJobs.Extensions.Http; +using Microsoft.Extensions.Logging; +using System.Net.Http; + +namespace Microsoft.Azure.Functions.V2.DI.Testing.AFV2 +{ + public static class AzureFunctionV2 + { + [FunctionName(nameof(AzureFunctionV2))] + public static HttpResponseMessage Run( + [HttpTrigger(AuthorizationLevel.Function, "get")] + HttpRequestMessage httpRequestMessage, + ILogger log, + [Inject] ITestService testService) + { + return httpRequestMessage.CreateResponse(testService.GetResult()); + } + } +} diff --git a/Microsoft.Azure.Functions.V2.DI.Testing/Microsoft.Azure.Functions.V2.DI.Testing.csproj b/Microsoft.Azure.Functions.V2.DI.Testing/Microsoft.Azure.Functions.V2.DI.Testing.csproj new file mode 100644 index 0000000..48d0a29 --- /dev/null +++ b/Microsoft.Azure.Functions.V2.DI.Testing/Microsoft.Azure.Functions.V2.DI.Testing.csproj @@ -0,0 +1,22 @@ + + + netstandard2.0 + v2 + + + + + + + + + + + PreserveNewest + + + PreserveNewest + Never + + + \ No newline at end of file diff --git a/Microsoft.Azure.Functions.V2.DI.Testing/Others/Startup.cs b/Microsoft.Azure.Functions.V2.DI.Testing/Others/Startup.cs new file mode 100644 index 0000000..3fe741c --- /dev/null +++ b/Microsoft.Azure.Functions.V2.DI.Testing/Others/Startup.cs @@ -0,0 +1,22 @@ +using Microsoft.Azure.Functions.V2.DI.Extensions; +using Microsoft.Azure.Functions.V2.DI.Testing.AFV2.Others; +using Microsoft.Azure.Functions.V2.DI.Testing.Service; +using Microsoft.Azure.WebJobs; +using Microsoft.Azure.WebJobs.Hosting; +using Microsoft.Extensions.DependencyInjection; + +[assembly: WebJobsStartup(typeof(Startup))] +namespace Microsoft.Azure.Functions.V2.DI.Testing.AFV2.Others +{ + internal class Startup : IWebJobsStartup + { + public void Configure(IWebJobsBuilder webJobsBuilder) + { + webJobsBuilder.AddInjectExtension(); + + webJobsBuilder.Services + .AddTransient() + .AddSingleton(); + } + } +} diff --git a/Microsoft.Azure.Functions.V2.DI.Testing/host.json b/Microsoft.Azure.Functions.V2.DI.Testing/host.json new file mode 100644 index 0000000..83ef024 --- /dev/null +++ b/Microsoft.Azure.Functions.V2.DI.Testing/host.json @@ -0,0 +1,8 @@ +{ + "version": "2.0", + "extensions": { + "http": { + "routePrefix": "" + } + } +} \ No newline at end of file diff --git a/Microsoft.Azure.Functions.V2.DI.Testing/local.settings.json b/Microsoft.Azure.Functions.V2.DI.Testing/local.settings.json new file mode 100644 index 0000000..4fce9ff --- /dev/null +++ b/Microsoft.Azure.Functions.V2.DI.Testing/local.settings.json @@ -0,0 +1,7 @@ +{ + "IsEncrypted": false, + "Values": { + "AzureWebJobsStorage": "UseDevelopmentStorage=true", + "FUNCTIONS_WORKER_RUNTIME": "dotnet" + } +} \ No newline at end of file diff --git a/Microsoft.Azure.Functions.V2.DI.sln b/Microsoft.Azure.Functions.V2.DI.sln new file mode 100644 index 0000000..c389dbe --- /dev/null +++ b/Microsoft.Azure.Functions.V2.DI.sln @@ -0,0 +1,43 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.27703.2000 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Azure.Functions.V2.DI", "Microsoft.Azure.Functions.V2.DI\Microsoft.Azure.Functions.V2.DI.csproj", "{A3F2C0FF-CA52-48EF-BEDD-F3BB088A0E63}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{C804529E-A674-46A6-BE65-71D5D155CC1B}" + ProjectSection(SolutionItems) = preProject + nuget.config = nuget.config + README.md = README.md + EndProjectSection +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Azure.Functions.V2.DI.Testing.Service", "Microsoft.Azure.Functions.V2.DI.Testing.Service\Microsoft.Azure.Functions.V2.DI.Testing.Service.csproj", "{7AFE5ABE-9E41-41D7-98B0-AC02D9AB71CB}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Azure.Functions.V2.DI.Testing", "Microsoft.Azure.Functions.V2.DI.Testing\Microsoft.Azure.Functions.V2.DI.Testing.csproj", "{70EA0FA4-89B9-4E2C-AA57-DCD9A9250563}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {A3F2C0FF-CA52-48EF-BEDD-F3BB088A0E63}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A3F2C0FF-CA52-48EF-BEDD-F3BB088A0E63}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A3F2C0FF-CA52-48EF-BEDD-F3BB088A0E63}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A3F2C0FF-CA52-48EF-BEDD-F3BB088A0E63}.Release|Any CPU.Build.0 = Release|Any CPU + {7AFE5ABE-9E41-41D7-98B0-AC02D9AB71CB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {7AFE5ABE-9E41-41D7-98B0-AC02D9AB71CB}.Debug|Any CPU.Build.0 = Debug|Any CPU + {7AFE5ABE-9E41-41D7-98B0-AC02D9AB71CB}.Release|Any CPU.ActiveCfg = Release|Any CPU + {7AFE5ABE-9E41-41D7-98B0-AC02D9AB71CB}.Release|Any CPU.Build.0 = Release|Any CPU + {70EA0FA4-89B9-4E2C-AA57-DCD9A9250563}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {70EA0FA4-89B9-4E2C-AA57-DCD9A9250563}.Debug|Any CPU.Build.0 = Debug|Any CPU + {70EA0FA4-89B9-4E2C-AA57-DCD9A9250563}.Release|Any CPU.ActiveCfg = Release|Any CPU + {70EA0FA4-89B9-4E2C-AA57-DCD9A9250563}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {C4376482-E91C-402C-B035-0403CE7576B1} + EndGlobalSection +EndGlobal diff --git a/Microsoft.Azure.Functions.V2.DI/Exceptions/MicrosoftAzureFunctionsDependencyInjectionException.cs b/Microsoft.Azure.Functions.V2.DI/Exceptions/MicrosoftAzureFunctionsDependencyInjectionException.cs new file mode 100644 index 0000000..ff33c70 --- /dev/null +++ b/Microsoft.Azure.Functions.V2.DI/Exceptions/MicrosoftAzureFunctionsDependencyInjectionException.cs @@ -0,0 +1,9 @@ +using System; + +namespace Microsoft.Azure.Functions.V2.DI.Exceptions +{ + internal class MicrosoftAzureFunctionsDependencyInjectionException : Exception + { + public MicrosoftAzureFunctionsDependencyInjectionException(string message) : base(message) { } + } +} diff --git a/Microsoft.Azure.Functions.V2.DI/Extensions/WebJobsBuilderExtensions.NetStandard2.0.cs b/Microsoft.Azure.Functions.V2.DI/Extensions/WebJobsBuilderExtensions.NetStandard2.0.cs new file mode 100644 index 0000000..f51e791 --- /dev/null +++ b/Microsoft.Azure.Functions.V2.DI/Extensions/WebJobsBuilderExtensions.NetStandard2.0.cs @@ -0,0 +1,22 @@ +using Microsoft.Azure.Functions.V2.DI.Filters; +using Microsoft.Azure.WebJobs; +using Microsoft.Azure.WebJobs.Host; +using Microsoft.Extensions.DependencyInjection; + +namespace Microsoft.Azure.Functions.V2.DI.Extensions +{ + public static class WebJobsBuilderExtensions + { + public static void AddInjectExtension(this IWebJobsBuilder webJobsBuilder) + { + webJobsBuilder.Services + .AddSingleton() + .AddSingleton() + .AddScoped() + .AddScoped() + .AddTransient(); + + webJobsBuilder.AddExtension(typeof(InjectConfiguration)); + } + } +} \ No newline at end of file diff --git a/Microsoft.Azure.Functions.V2.DI/Filters/ScopeCleanupFilter.cs b/Microsoft.Azure.Functions.V2.DI/Filters/ScopeCleanupFilter.cs new file mode 100644 index 0000000..9589820 --- /dev/null +++ b/Microsoft.Azure.Functions.V2.DI/Filters/ScopeCleanupFilter.cs @@ -0,0 +1,33 @@ +using System; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Azure.WebJobs.Host; + +namespace Microsoft.Azure.Functions.V2.DI.Filters +{ + internal class ScopeCleanupFilter : IFunctionInvocationFilter, IFunctionExceptionFilter + { + public Task OnExceptionAsync(FunctionExceptionContext exceptionContext, CancellationToken cancellationToken) + { + RemoveScope(exceptionContext.FunctionInstanceId); + return Task.CompletedTask; + } + + public Task OnExecutedAsync(FunctionExecutedContext executedContext, CancellationToken cancellationToken) + { + RemoveScope(executedContext.FunctionInstanceId); + return Task.CompletedTask; + } + + public Task OnExecutingAsync(FunctionExecutingContext executingContext, CancellationToken cancellationToken) => + Task.CompletedTask; + + private void RemoveScope(Guid id) + { + if (InjectBindingProvider.Scopes.TryRemove(id, out var scope)) + { + scope.Dispose(); + } + } + } +} diff --git a/Microsoft.Azure.Functions.V2.DI/FunctionExtensions/InjectExtension/InjectAttribute.cs b/Microsoft.Azure.Functions.V2.DI/FunctionExtensions/InjectExtension/InjectAttribute.cs new file mode 100644 index 0000000..3e2aa0a --- /dev/null +++ b/Microsoft.Azure.Functions.V2.DI/FunctionExtensions/InjectExtension/InjectAttribute.cs @@ -0,0 +1,9 @@ +using System; +using Microsoft.Azure.WebJobs.Description; + +namespace Microsoft.Azure.Functions.V2.DI +{ + [Binding] + [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false)] + public class InjectAttribute : Attribute {} +} diff --git a/Microsoft.Azure.Functions.V2.DI/FunctionExtensions/InjectExtension/InjectBinding.NetStandard2.0.cs b/Microsoft.Azure.Functions.V2.DI/FunctionExtensions/InjectExtension/InjectBinding.NetStandard2.0.cs new file mode 100644 index 0000000..f45ae59 --- /dev/null +++ b/Microsoft.Azure.Functions.V2.DI/FunctionExtensions/InjectExtension/InjectBinding.NetStandard2.0.cs @@ -0,0 +1,26 @@ +using Microsoft.Azure.Functions.V2.DI.Models; +using Microsoft.AspNetCore.Http.Internal; +using Microsoft.Azure.WebJobs.Host.Bindings; +using System.Collections.Generic; +using System.Linq; + +namespace Microsoft.Azure.Functions.V2.DI +{ + internal partial class InjectBinding + { + private static FunctionRequest GetFunctionRequest(BindingContext context) + { + var defaultHttpRequest = context.BindingData.TryGetValue("$request", out var defaultHttpRequestObject) + ? (DefaultHttpRequest)defaultHttpRequestObject + : null; + + if (defaultHttpRequest == null) return null; + + return new FunctionRequest + { + Headers = defaultHttpRequest.Headers + .Select(header => new KeyValuePair>(header.Key, header.Value)) + }; + } + } +} \ No newline at end of file diff --git a/Microsoft.Azure.Functions.V2.DI/FunctionExtensions/InjectExtension/InjectBinding.cs b/Microsoft.Azure.Functions.V2.DI/FunctionExtensions/InjectExtension/InjectBinding.cs new file mode 100644 index 0000000..7519bef --- /dev/null +++ b/Microsoft.Azure.Functions.V2.DI/FunctionExtensions/InjectExtension/InjectBinding.cs @@ -0,0 +1,64 @@ +using System; +using System.Threading.Tasks; +using Microsoft.Azure.Functions.V2.DI.Exceptions; +using Microsoft.Azure.Functions.V2.DI.Models; +using Microsoft.Azure.WebJobs.Host.Bindings; +using Microsoft.Azure.WebJobs.Host.Protocols; +using Microsoft.Extensions.DependencyInjection; + +namespace Microsoft.Azure.Functions.V2.DI +{ + internal partial class InjectBinding : IBinding + { + private readonly Type _type; + private readonly IServiceProvider _serviceProvider; + + internal InjectBinding(IServiceProvider serviceProvider, Type type) + { + _type = type; + _serviceProvider = serviceProvider; + } + + public bool FromAttribute => true; + + public Task BindAsync(object value, ValueBindingContext context) => + Task.FromResult((IValueProvider)new InjectValueProvider(value)); + + public async Task BindAsync(BindingContext context) + { + await Task.Yield(); + var scope = InjectBindingProvider.Scopes.GetOrAdd(context.FunctionInstanceId, (_) => _serviceProvider.CreateScope()); + + var functionsContextResolver = scope.ServiceProvider.GetService(); + + if (functionsContextResolver == null) throw new MicrosoftAzureFunctionsDependencyInjectionException( + $"You must register '{nameof(IFunctionsContextResolver)}'. " + + $"You can use '{nameof(FunctionsContextResolver)}' from this package.'"); + + functionsContextResolver.FunctionContext = new FunctionContext + { + FunctionInstanceId = context.FunctionInstanceId.ToString(), + CurrentScope = scope, + FunctionRequest = GetFunctionRequest(context) + }; + + var value = scope.ServiceProvider.GetRequiredService(_type); + return await BindAsync(value, context.ValueContext); + } + + public ParameterDescriptor ToParameterDescriptor() => new ParameterDescriptor(); + + private class InjectValueProvider : IValueProvider + { + private readonly object _value; + + public InjectValueProvider(object value) => _value = value; + + public Type Type => _value.GetType(); + + public Task GetValueAsync() => Task.FromResult(_value); + + public string ToInvokeString() => _value.ToString(); + } + } +} diff --git a/Microsoft.Azure.Functions.V2.DI/FunctionExtensions/InjectExtension/InjectBindingProvider.NetStandard2.0.cs b/Microsoft.Azure.Functions.V2.DI/FunctionExtensions/InjectExtension/InjectBindingProvider.NetStandard2.0.cs new file mode 100644 index 0000000..863976e --- /dev/null +++ b/Microsoft.Azure.Functions.V2.DI/FunctionExtensions/InjectExtension/InjectBindingProvider.NetStandard2.0.cs @@ -0,0 +1,28 @@ +#if NETSTANDARD2_0 +using System; +using System.Collections.Concurrent; +using System.Threading.Tasks; +using Microsoft.Azure.WebJobs.Host.Bindings; +using Microsoft.Extensions.DependencyInjection; + +namespace Microsoft.Azure.Functions.V2.DI +{ + internal class InjectBindingProvider : IBindingProvider + { + public static readonly ConcurrentDictionary Scopes = new ConcurrentDictionary(); + + private readonly IServiceProvider _serviceProvider; + + public InjectBindingProvider(IServiceProvider serviceProvider) + { + _serviceProvider = serviceProvider; + } + + public Task TryCreateAsync(BindingProviderContext context) + { + IBinding binding = new InjectBinding(_serviceProvider, context.Parameter.ParameterType); + return Task.FromResult(binding); + } + } +} +#endif \ No newline at end of file diff --git a/Microsoft.Azure.Functions.V2.DI/FunctionExtensions/InjectExtension/InjectConfiguration.NetStandard2.0.cs b/Microsoft.Azure.Functions.V2.DI/FunctionExtensions/InjectExtension/InjectConfiguration.NetStandard2.0.cs new file mode 100644 index 0000000..fba10dc --- /dev/null +++ b/Microsoft.Azure.Functions.V2.DI/FunctionExtensions/InjectExtension/InjectConfiguration.NetStandard2.0.cs @@ -0,0 +1,17 @@ +#if NETSTANDARD2_0 +using Microsoft.Azure.WebJobs.Host.Config; + +namespace Microsoft.Azure.Functions.V2.DI +{ + internal class InjectConfiguration : IExtensionConfigProvider + { + private readonly InjectBindingProvider _bindingProvider; + + public InjectConfiguration(InjectBindingProvider bindingProvider) => _bindingProvider = bindingProvider; + + public void Initialize(ExtensionConfigContext context) => context + .AddBindingRule() + .Bind(_bindingProvider); + } +} +#endif \ No newline at end of file diff --git a/Microsoft.Azure.Functions.V2.DI/Implementations/FunctionsContextResolver.cs b/Microsoft.Azure.Functions.V2.DI/Implementations/FunctionsContextResolver.cs new file mode 100644 index 0000000..a11be6e --- /dev/null +++ b/Microsoft.Azure.Functions.V2.DI/Implementations/FunctionsContextResolver.cs @@ -0,0 +1,9 @@ +using Microsoft.Azure.Functions.V2.DI.Models; + +namespace Microsoft.Azure.Functions.V2.DI +{ + public partial class FunctionsContextResolver : IFunctionsContextResolver + { + public FunctionContext FunctionContext { get; set; } + } +} \ No newline at end of file diff --git a/Microsoft.Azure.Functions.V2.DI/Implementations/MockResolver.cs b/Microsoft.Azure.Functions.V2.DI/Implementations/MockResolver.cs new file mode 100644 index 0000000..d4b11d9 --- /dev/null +++ b/Microsoft.Azure.Functions.V2.DI/Implementations/MockResolver.cs @@ -0,0 +1,26 @@ +using System.Linq; + +namespace Microsoft.Azure.Functions.V2.DI +{ + public class MockResolver : IMockResolver + { + private readonly IFunctionsContextResolver _functionsContextResolver; + + public MockResolver(IFunctionsContextResolver functionsContextResolver) + { + _functionsContextResolver = functionsContextResolver; + } + + public bool IsMockEnabled() + { + var headers = _functionsContextResolver.FunctionContext?.FunctionRequest?.Headers?.ToList(); + + if (headers == null) return false; + + var mockHeader = headers.FirstOrDefault(x=> x.Key == "X-Mocking-Services").Value?.FirstOrDefault(f=> f == "Enabled") ?? + headers.FirstOrDefault(x => x.Key == "X-MOCK").Value?.FirstOrDefault(f => f == "Enabled"); + + return mockHeader != null; + } + } +} diff --git a/Microsoft.Azure.Functions.V2.DI/Interfaces/IFunctionsContextResolver.cs b/Microsoft.Azure.Functions.V2.DI/Interfaces/IFunctionsContextResolver.cs new file mode 100644 index 0000000..780af6c --- /dev/null +++ b/Microsoft.Azure.Functions.V2.DI/Interfaces/IFunctionsContextResolver.cs @@ -0,0 +1,9 @@ +using Microsoft.Azure.Functions.V2.DI.Models; + +namespace Microsoft.Azure.Functions.V2.DI +{ + public partial interface IFunctionsContextResolver + { + FunctionContext FunctionContext { get; set; } + } +} \ No newline at end of file diff --git a/Microsoft.Azure.Functions.V2.DI/Interfaces/IMockResolver.cs b/Microsoft.Azure.Functions.V2.DI/Interfaces/IMockResolver.cs new file mode 100644 index 0000000..8bc6264 --- /dev/null +++ b/Microsoft.Azure.Functions.V2.DI/Interfaces/IMockResolver.cs @@ -0,0 +1,7 @@ +namespace Microsoft.Azure.Functions.V2.DI +{ + public interface IMockResolver + { + bool IsMockEnabled(); + } +} diff --git a/Microsoft.Azure.Functions.V2.DI/Microsoft.Azure.Functions.V2.DI.csproj b/Microsoft.Azure.Functions.V2.DI/Microsoft.Azure.Functions.V2.DI.csproj new file mode 100644 index 0000000..d983746 --- /dev/null +++ b/Microsoft.Azure.Functions.V2.DI/Microsoft.Azure.Functions.V2.DI.csproj @@ -0,0 +1,10 @@ + + + netstandard2.0 + 7.2 + + + + + + diff --git a/Microsoft.Azure.Functions.V2.DI/Models/FunctionContext.cs b/Microsoft.Azure.Functions.V2.DI/Models/FunctionContext.cs new file mode 100644 index 0000000..954a6b8 --- /dev/null +++ b/Microsoft.Azure.Functions.V2.DI/Models/FunctionContext.cs @@ -0,0 +1,11 @@ +using Microsoft.Extensions.DependencyInjection; + +namespace Microsoft.Azure.Functions.V2.DI.Models +{ + public class FunctionContext + { + public string FunctionInstanceId { get; set; } + public FunctionRequest FunctionRequest { get; set; } + public IServiceScope CurrentScope { get; set; } + } +} \ No newline at end of file diff --git a/Microsoft.Azure.Functions.V2.DI/Models/FunctionRequest.cs b/Microsoft.Azure.Functions.V2.DI/Models/FunctionRequest.cs new file mode 100644 index 0000000..59de861 --- /dev/null +++ b/Microsoft.Azure.Functions.V2.DI/Models/FunctionRequest.cs @@ -0,0 +1,10 @@ +using System.Collections.Generic; + +namespace Microsoft.Azure.Functions.V2.DI.Models +{ + public class FunctionRequest + { + public IEnumerable>> Headers { get; set; } = + new List>>(); + } +} \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..feaa240 --- /dev/null +++ b/README.md @@ -0,0 +1,8 @@ +# Introduction +Implementation of depency injection for Microsoft Azure Functions + +# Getting Started +Just get it and build it. I was using VS 2017 Enterprise. + +# Build and Test +Take a look at the tests to understand how to use it. diff --git a/nuget.config b/nuget.config new file mode 100644 index 0000000..bfc6676 --- /dev/null +++ b/nuget.config @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + \ No newline at end of file