2015-04-12 62 views
0

我正在使用ASP.NET和AngularJS的REST API創建項目。如何避免構造函數的調用?

我的資料庫:

Class MyRepository { 
    private int myVariable; 
    public MyRepository() { 
     myVariable = 100; 
    } 

    public int getMyVariable() { 
     return myVariable; 
    } 

    public int Update(int data) { 
     myVariable = data; 
     return data; 
    } 
} 

控制器:

public Class MyController : ApiController { 
    private MyRepository repository = new MyRepository(); 

    [Route("myRoute")] 
    public int getVariable() { 
     return getMyVariable(); 
    } 

    [Route("myRoute")] 
    [HttpPut] 
    public IHttpActionResult Update(int data) 
    { 
     data = repository.Update(data); 
     return Ok(data); 
    } 
} 

方法在JS服務:

getMyNumber = function() { 
    return $http.get("/myRoute"); 
}; 

updateMyNumber = function (number) { 
    return $http.put("/myRoute", number); 
} 

首先我打電話功能。結果是100(好)。然後我將它更新爲50.有了一個斷點,我可以看到它在存儲庫中確實是50。當我再次調用函數時,結果爲100.

看起來像我的每個請求都調用了MyController的構造函數。如果是這樣,更新數據和更新數據的方式是什麼?

+0

考慮添加一個構造函數到你的ApiController並通過依賴注入注入你的版本庫的一個實例。 –

回答

0

是的,控制器的範圍是針對每個請求的,因此您每次請求時都會將其與庫對象一起更新。這聽起來像你正在避免需要一個數據庫,並且不需要超出應用程序生命週期的任何持久性。所以在這種情況下,你應該在應用程序生命週期範圍內存儲一個值,這意味着處理併發性。也許你需要的是這裏描述的解決方案之一:http://www.wiktorzychla.com/2010/12/container-based-pseudosingletons-in.html