Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I create non static Azure function class in C#, what are the consequences?

This non static class is required for constructor injection in Azure function and collection of custom telemetry events.

If we create an azure function app in visual studio, it creates default with static keyword like this:

public static async Task<IActionResult> Run(
                [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
                ILogger log)
{
     telemetryClient.TrackEvent(new Exception("Function started"));
}

But to use constructor dependency injection (for Temeltry client, i am using it), we need to remove static keyword.

public Function1(TelemetryClient telemetryClient)
        {
            _telemetryClient = telemetryClient;
        }
like image 679
Shailendra Avatar asked Jan 20 '20 10:01

Shailendra


People also ask

Why Azure functions are static by default?

but why it is declared as static by default? By default, whenever you create an Azure Function, it comes in a template with a static class and a static method. Microsoft enabled instance methods for Azure Functions, now we are able to have non-static classes and methods for our functions.

Can we create non-static method in static class?

We can use 'i' value throughout the program. Static is like constant but for static memory is allocated and values assigned at run time. We can create a static method inside the non-static class.

Can non-static class have static methods C#?

Static MembersA non-static class can contain static methods, fields, properties, or events. The static member is callable on a class even when no instance of the class has been created. The static member is always accessed by the class name, not the instance name.

What is the difference between non-static and static classes?

Difference between static and non-static classStatic class is defined using static keyword. Non-Static class is not defined by using static keyword. In static class, you are not allowed to create objects. In non-static class, you are allowed to create objects using new keyword.


1 Answers

Previously, Azure Functions only supported static classes/methods. This restriction made DI via constructor impossible. However later the support for non-static classes/methods was implemented (see Support Instance Functions).

So if you need to use DI via constructor, just change it to non-static. There are no consequences.

like image 173
Ivan Yang Avatar answered Sep 23 '22 17:09

Ivan Yang