内容简介: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
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 benetcoreapp3.1
- The
AzureFunctionsVersion
should bev3
and - The
Microsoft.NET.Sdk.Functions
package should be version3.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
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。