Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DI in Azure Functions

I have some class libraries that I use in my ASP.NET Web API app that handle all my backend stuff e.g. CRUD operations to multiple databases like Azure SQL Database, Cosmos DB, etc.

I don't want to re-invent the wheel and able to use them in a new Azure Functions that I'm creating in Visual Studio 2017. All my repository methods use an interface. So, how will I implement dependency injection in my new Azure function?

I'm not seeing any support for DI but I'm a bit confused. It appears Azure Functions are based on the same SDK as WebJobs and I think last year Microsoft had started supporting DI in WebJobs - I know for sure because I implemented it using Ninject.

Is there way around this so that I can use my existing libraries in my new Azure Functions project?

like image 377
Sam Avatar asked Aug 28 '17 05:08

Sam


People also ask

What is DI in Dot Net core?

ASP.NET Core supports the dependency injection (DI) software design pattern, which is a technique for achieving Inversion of Control (IoC) between classes and their dependencies. For more information specific to dependency injection within MVC controllers, see Dependency injection into controllers in ASP.NET Core.

How does .NET DI work?

The . NET Core built-in DI provides an IoC mechanism, often referred to as a “Container”, for offloading the instantiation, injection, and lifetime management of the application's dependencies. You invert the control of component instantiation from the consumers to the container, hence “Inversion of Control”.

What is host JSON in Azure function?

The host. json metadata file contains configuration options that affect all functions in a function app instance. This article lists the settings that are available starting with version 2. x of the Azure Functions runtime.


2 Answers

I see these two techniques in addition to the service locator (anti)pattern. I asked the Azure Functions team for their comments as well.

https://blog.wille-zone.de/post/azure-functions-dependency-injection/

https://blog.wille-zone.de/post/azure-functions-proper-dependency-injection/

like image 111
Sam Avatar answered Oct 03 '22 05:10

Sam


There is an open feature request on the GitHub pages for Azure Functions concerning this matter.

However, the way I'm approaching this is using some kind of 'wrapper' entry point, resolve this using the service locator and and start the function from there.

This looks a bit like this (simplified)

var builder = new ContainerBuilder(); //register my types  var container = builder.Build();  using(var scope = container.BeginLifetimeScope()) {   var functionLogic = scope.Resolve<IMyFunctionLogic>();    functionLogic.Execute(); } 

This is a bit hacky of course, but it's the best there is until there is at the moment (to my knowledge).

like image 26
Jan_V Avatar answered Oct 03 '22 05:10

Jan_V