Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET and static method in controller

Tags:

Assume that WebApi2 controller has a SearchClient which is configured in scoped-lifestyle dependency on startup.

public class SearchController : ApiController {

    private readonly SearchClient _indexClient;

    public SearchController(SearchClient client) {
        _indexClient = client; // dependency injected
    }

    public IEnumerable<string> Get(string keyword){
        return SearchDocuments(_indexClient, keyword);
    }

    public static IEnumerable<string> SearchDocuments(SearchClient indexClient, string text)
    {
        return indexClient.Search(text);
    }
}

As we can see, SearchDocuments method has static keyword.

My questions are;

  1. How can we decide whether static method is good or bad?
  2. Is static method safe or recommended in such a multiple-accessed web environment?
  3. What about async static method in web environment? Is it different from async method?
like image 571
Youngjae Avatar asked Jul 12 '17 11:07

Youngjae


People also ask

CAN controller method static?

Yes you can but you need to make a static class and access the static class inside the controller. You can just put it in a class like below. Then you can call it from any of your controllers, no matter what their base class is.

Can action method be static in MVC?

The one restriction on action method is that they have to be instance method, so they cannot be static methods. Also there is no return value restrictions. So you can return the string, integer, etc.

What is static method in asp net?

A static method in C# is a method that keeps only one copy of the method at the Type level, not the object level. That means, all instances of the class share the same copy of the method and its data.

Is ViewBag static?

The ViewBag is a dynamic property that takes advantage of new dynamic features in C# 4.0.


1 Answers

How can we decide whether static method is good or bad?

Static methods in web applications are just like static methods in desktop applications. There is no difference in how they are handled or interpreted once they run in a web application. So they are not bad or good, you use them for everything that is not instance-specific.

Is static method safe or recommended in such a multiple-accessed web environment?

static fields or properties can have unwanted side effects when user or session specific data is stored in it since static variables are shared across sessions. But this is a method, and methods don't have a shared state. Hence they are safe to use in a multi-user/multi-session environment.

What about async static method in web environment? Is it different from async method?

Nothing other than already described in the answer to your first question.

like image 177
Patrick Hofman Avatar answered Sep 29 '22 23:09

Patrick Hofman