How can I use the new DI to inject an ILogger into an Azure Function using IWebJobsStartup?

前端 未结 5 1793
后悔当初
后悔当初 2021-02-04 03:18

I am using Azure Function v2. Here is my function that uses the constructor injection:

public sealed class FindAccountFunction
{
    private readonl         


        
5条回答
  •  执笔经年
    2021-02-04 03:30

    UPDATE

    Reference Use dependency injection in .NET Azure Functions

    Registering services

    To register services, you can create a configure method and add components to an IFunctionsHostBuilder instance. The Azure Functions host creates an IFunctionsHostBuilder and passes it directly into your configured method.

    To register your configure method, you must add an assembly attribute that specifies the type for your configure method using the FunctionsStartup attribute.

    So in this case

    [assembly: FunctionsStartup(typeof(MyNamespace.Startup))]    
    namespace MyNamespace {
        public class Startup : FunctionsStartup {
            public override void Configure(IFunctionsHostBuilder builder) {
                //  ** Registers the ILogger instance **
                builder.Services.AddLogging();
    
                //  Registers the application settings' class.
                //...
    
                //...omitted for brevity    
            }
        }
    }
    

    ORIGINAL

    I believe since you have access to the service collection, you should be able to add logging to it

    public void Configure(IWebJobsBuilder webJobsBuilder) {       
    
        //  ** Registers the ILogger instance **
        webJobsBuilder.Services.AddLogging();
    
        //OR
        //webJobsBuilder.Services.AddLogging(builder => {
        //    //...
        //});
    
        //  Registers the application settings' class.
        //...
    
        //...removed for brevity
    }
    

    and having anILoggerFactory in the Function's constructor.

    //...
    
    //Ctor
    public FindAccountFunction(ILoggerFactory loggerFactory, IMapper mapper, IAccountWorkflow accountWorkflow) {
        m_logger = loggerFactory.CreateLogger();
        m_mapper = mapper;
        m_accountWorkflow = accountWorkflow;
    }
    
    //...
    

提交回复
热议问题