Azure / azure-functions-host

The host/runtime that powers Azure Functions
https://functions.azure.com
MIT License
1.92k stars 441 forks source link

Add support for app level initialization logic #586

Open davidebbo opened 8 years ago

davidebbo commented 8 years ago

e.g. in this thread, the user needs to call ThreadPool.SetMinThreads, and currently we have no good place to make App Domain init time calls.

Of course, that gives user potential to make some bad calls, but that's a small concern compared to the scenarios that can unblock (and the could make the same calls in a function anyway).

drekuru commented 3 years ago

Sorry if a bit late on this, but just had this issue. So this is how I got code to run on startup and when you need some dependency injection and you need it to start before any function triggers.

NB: This only works if your code is either very short lived or it can be a singleton for the lifetime of the node.

public class Startup : FunctionsStartup
    {

        public override void Configure(IFunctionsHostBuilder builder)
        {
            // create a new service collection -> NOT using builder.Services
            var serviceCollection = new ServiceCollection();

            // add the min DI items you need
            serviceCollection.AddMinimalItemsINeedExtension();

            // build the provider
            var provider = serviceCollection.BuildServiceProvider();

            // get the dependency
            var dependency = provider.GetService<IMyDependency>();

            // run your startup code
            dependency.RunTheStartUpCodeIWant();

            // either dispose of this or add the singleton to the builder
            // so your function app can access it.
            builder.Services.AddSingleton<IMyDependency>(dependency);
        }
}

Hacky I know but it works.

@ianadavies this is for C# functions yea?

ianadavies commented 3 years ago

@drekuru , Yes its c#

drekuru commented 2 years ago

@mathewc any updates here?

drekuru commented 1 year ago

@ahmelsayed any updates here? It's been over 6 years.