[英]ASP.NET and static method in controller
假設WebApi2控制器具有SearchClient
其在作用域生活方式依賴性配置在啟動時。
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);
}
}
我們可以看到, SearchDocuments
方法有static
關鍵字。
我的問題是;
static
方法是好還是壞? static
方法是安全的還是推薦的? async static
方法呢? 它與async
方法不同嗎? 我們如何判斷靜態方法是好還是壞?
Web應用程序中的靜態方法就像桌面應用程序中的靜態方法一樣。 一旦在Web應用程序中運行,它們的處理方式或解釋方式就沒有區別。 因此它們不壞或不好,您將它們用於非特定於實例的所有內容。
在這樣一個多訪問的Web環境中,靜態方法是安全的還是推薦的?
static
字段或屬性在用戶或會話特定數據存儲在其中時可能會產生不必要的副作用,因為static
變量是跨會話共享的。 但這是一種方法,方法沒有共享狀態。 因此,它們可安全地用於多用戶/多會話環境中。
那么Web環境中的異步靜態方法呢? 它與異步方法不同嗎?
除了您在第一個問題的答案中已經描述的以外,沒有其他內容。
只是添加已經提供的答案。
在控制器上使用靜態方法並沒有真正添加任何值,並且在給定方案中實際上並不需要。
考慮在控制器中抽象顯式依賴項。
public class SearchController : ApiController {
private readonly ISearchClient indexClient;
public SearchController(ISearchClient client) {
indexClient = client; // dependency injected
}
public IEnumerable<string> Get(string keyword){
return indexClient.Search(keyword);
}
}
這也將允許在測試和重構時松散耦合和更多靈活性,因為依賴性的實現可以在不必觸摸控制器的情況下改變。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.