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;
static
method is good or bad? static
method safe or recommended in such a multiple-accessed web environment? async static
method in web environment? Is it different from async
method?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.
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.
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.
The ViewBag is a dynamic property that takes advantage of new dynamic features in C# 4.0.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With