Dependency Injection in Azure Functions with C#

栏目: IT技术 · 发布时间: 5年前

内容简介:The next few lines of code added is the most easily forgotten but they are essential to ensuring that your project uses the code in Startup:Our Startup class needs to implement

Dependency Injection in Azure Functions with C#

One of my favourite features of Azure Functions v2 and above is the ability to include a Startup class. Why is this cool you may ask? Well, it means that you can use .NET Core's built-in Dependency Injection (DI). This then means that project architecture can look remarkably like ASP.NET Core web apps. DI also makes testing easier as dependencies can be mocked. In this post, I'll show you how you can quickly add DI to an Azure Function.

Note: Azure Functions v3.0 became GA in January 2020. This means that you can now use .NET 3.1 and Node 12 in your Azure Functions. They still don't support the new System.Text.Json but that should come in time.

Adding a Startup class to an Azure Function

Start with an existing Azure Function project or create a new project from the CLI /IDE. You can choose any type of Function but for ease, I would use an HTTP Trigger Function as it will be easier to test.

If you are using .NET Core 3.1, it's worth checking that your new function is set up correctly in the .csproj file.

  • The TargetFramework should be netcoreapp3.1
  • The AzureFunctionsVersion should be v3 and
  • The Microsoft.NET.Sdk.Functions package should be version 3.0.3 or above

We will need to include a "Microsoft.Azure.Functions.Extensions" nuget package. You can add this using the package manager or you can add <PackageReference Include="Microsoft.Azure.Functions.Extensions" Version="1.0.0" /> to the <ItemGroup> node in the .csproj .

In the root of the project, add a new file called "Startup.cs". The default code in the new class should look similar to the code below, only with a namespace equal to the name of your project.

namespace DependencyInjectionFunctions
{
   public class Startup
   {      
   }
}

The next few lines of code added is the most easily forgotten but they are essential to ensuring that your project uses the code in Startup:

using DependencyInjectionFunctions;
using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;

[assembly: FunctionsStartup(typeof(Startup))]
namespace DependencyInjectionFunctions
{
   public class Startup : FunctionsStartup
   {
      public override void Configure(IFunctionsHostBuilder builder)
      {
         throw new System.NotImplementedException();
      }
   }
}

Our Startup class needs to implement FunctionsStartup which itself implements IWebJobStartup .

We can now start to register our dependencies to the IoC container, which resolves our dependencies at runtime, like so, where IRepository is an example name of an interface and Repository would be the class that you would like injected that implements the interface:

using DependencyInjectionFunctions;
using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;

[assembly: FunctionsStartup(typeof(Startup))]
namespace DependencyInjectionFunctions
{
   public class Startup : FunctionsStartup
   {
      public override void Configure(IFunctionsHostBuilder builder)
      {
         builder.Services.AddSingleton<IRepository, Repository>();
         // or one of the options below
         // builder.Services.AddScoped<IRepository, Repository>();
         // builder.Services.AddTransient<IRepository, Repository>();
         builder.Services.AddLogging();
      }
   }

public interface IRepository
{
    string GetData();
}
public class Repository : IRepository
{
   public string GetData()
   {
       return "some data!";
   }
 }
}

If you are unsure as to whether to register services as scoped, transient or singleton, there is this great explanation on StackOverflow .

Middleware, such as logging, can also be added in the Startup as shown above.

Using injected classes

Let's look at how these dependencies can be used in an HTTP Trigger function. Add the following lines of code, and their references, to the HttpTrigger you added at the beginning.

public class HttpTriggerFunction
{
  private readonly IRepository _repository;

  public HttpTriggerFunction(IRepository repository)
  {
      _repository = repository;
  }

  [FunctionName("HttpTrigger")]
  public async Task<IActionResult> Run(
      [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
      ILogger log)
  {
     log.LogInformation("C# HTTP trigger function processed a request.");
     var someData = _repository.GetData();
     return new OkObjectResult(someData);
  }
}

If you've used Azure Functions before, you may remember that classes used to be static classes. This is no longer the case. To enable DI we need to have a constructor, for constructor injection , and a static class cannot have a constructor.

In the code above, you can see that we have added a private, readonly property with the injected interface as its type. Then we have the interface as a parameter in the constructor. The IoC container will inject the correct implementation of the interface based on the setup in the Startup class.

Our class is now ready for us to use with the Function! You can test this using a program such as Postman .

To do this, run the function from the CLI using the func start command.

If you followed the along with the code above it should be http://localhost:7071/api/HttpTrigger . Call this URL from Postman, using a GET or a POST request, and the response will be "some data!".

The ability to use Dependency Injection in Azure Functions means that solutions can be better written using proven design patterns for better maintainability and testability. Enjoy!

Authors


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

长尾理论

长尾理论

[美]克里斯•安德森 (Chris Anderson) / 乔江涛、石晓燕 / 中信出版社 / 2012 / 68.00元

网络经济正如火如荼地发展着,长尾理论无疑成为当代商务人士最为关注的焦点之一。不论是关于长尾理论的溢美还是论战,都代表了其备受关注的程度。 《长尾理论》是克里斯•安德森对这些争论的最明确的回答。在书中,他详细阐释了长尾的精华所在,指出商业和文化的未来不在于传统需求曲线上那个代表“畅销商品”的头部,而是那条代表“冷门商品”的经常被人遗忘的长尾。他还揭示了长尾现象是如何从工业资本主义原动力——规模......一起来看看 《长尾理论》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

SHA 加密
SHA 加密

SHA 加密工具

html转js在线工具
html转js在线工具

html转js在线工具