DI in Azure Functions

后端 未结 11 1041
庸人自扰
庸人自扰 2020-12-25 10:43

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

相关标签:
11条回答
  • 2020-12-25 11:29

    I think this is a better solution:

    https://github.com/junalmeida/autofac-azurefunctions https://www.nuget.org/packages/Autofac.Extensions.DependencyInjection.AzureFunctions

    Install the NuGet in your project and then make a Startup.cs and put this in it:

    [assembly: FunctionsStartup(typeof(Startup))]
    
    public class Startup
    {
        public override void Configure(IFunctionsHostBuilder builder)
        {
            builder
                .UseAppSettings() // this is optional, this will bind IConfiguration in the container.
                .UseAutofacServiceProviderFactory(ConfigureContainer);
        }
    
        private void ConfigureContainer(ContainerBuilder builder)
        {
             // do DI registration against Autofac like normal! (builder is just the normal ContainerBuilder from Autofac)
        }
        ...
    

    Then in your function code you can do normal constructor injection via DI:

    public class Function1 : Disposable
    {
        public Function1(IService1 service1, ILogger logger)
        {
            // logger and service1 injected via autofac like normal
            // ...
        }
    
        [FunctionName(nameof(Function1))]
        public async Task Run([QueueTrigger("myqueue-items", Connection = "AzureWebJobsStorage")]string myQueueItem)
        {
            //...
    
    0 讨论(0)
  • 2020-12-25 11:31

    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/

    0 讨论(0)
  • 2020-12-25 11:32

    I would like to add my 2 cents to it. I used the technique that it's used by Host injecting ILogger. If you look at the Startup project I created GenericBindingProvider that implements IBindingProvider. Then for each type I want to be injected I register it as follow:

    builder.Services.AddTransient<IWelcomeService, WelcomeService>();
    builder.Services.AddSingleton<IBindingProvider, GenericBindingProvider<IWelcomeService>>();
    

    The downside is that you need to register the type you want to be injected into the function twice.

    Sample code:

    Azure Functions V2 Dependency Injection sample

    0 讨论(0)
  • 2020-12-25 11:36

    AzureFunctions.Autofac is very easy to use.

    Just add a config file:

    public class DIConfig
    {
        public DIConfig(string functionName)
        {
            DependencyInjection.Initialize(builder =>
            {
                builder.RegisterType<Sample>().As<ISample>();
                ...
            }, functionName);
        }
    }
    

    Add the DependencyInjectionConfig attribute then inject:

    [DependencyInjectionConfig(typeof(DIConfig))]
    public class MyFunction
    {
        [FunctionName("MyFunction")]
        public static HttpResponseMessage Run([HttpTrigger(AuthorizationLevel.Function, "get", Route = null)]HttpRequestMessage request, 
                                              TraceWriter log, 
                                              [Inject]ISample sample)
        {
    

    https://github.com/introtocomputerscience/azure-function-autofac-dependency-injection

    0 讨论(0)
  • 2020-12-25 11:36

    Support for Dependency injection begins with Azure Functions 2.x which means Dependency Injection in Azure function can now leverage .NET Core Dependency Injection features.

    Before you can use dependency injection, you must install the following NuGet packages:

    • Microsoft.Azure.Functions.Extensions
    • Microsoft.NET.Sdk.Functions

    Having Dependency Injection eases things like DBContext, Http client usage (Httpclienfactory), Iloggerfactory, cache support etc.

    Firstly, update the Startup class as shown below

    namespace DemoApp
    {
        public class Startup: FunctionsStartup
        {
            public override void Configure(IFunctionsHostBuilder builder)
            {
                builder.Services.AddScoped<IHelloWorld, HelloWorld>();
    
                // Registering Serilog provider
                var logger = new LoggerConfiguration()
                    .WriteTo.Console()
                    .CreateLogger();
                builder.Services.AddLogging(lb => lb.AddSerilog(logger));
                //Reading configuration section can be added here etc.
            }
        }
    }
    

    Secondly, Removal of Static keyword in Function class and method level

    public class DemoFunction
    {
        private readonly IHelloWorld _helloWorld;
        public DemoFunction(IHelloWorld helloWorld)
        {
            _helloWorld = helloWorld;
        }
    
        [FunctionName("HttpDemoFunction")]
        public async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");
        }
    

    If we look into above e.g. IHelloWorld is injected using .NET Core DI

    **Note:**In-spite of having latest version of Azure function v3 for Dependency Injection to enable few steps are manual as shown above

    Sample code on github can be found here

    0 讨论(0)
提交回复
热议问题