2012-08-26 40 views
1

我正在使用ASP.NET Web API & Ninject進行REST服務,儘管我懷疑這可能是比我的IoC框架特有的任何更一般的IoC問題。我有多個對象需要訪問用戶實體的一個簡單的緩存:Web API中的長期對象的依賴注入?

public class UserCache 
{ 
    private IList<User> users; 
    private IUserRepositoryFactory factory; 

    [Inject] 
    public UserCache(IUserRepositoryFactory factory) 
    { 
     this.factory = factory; 
     this.users = new List<User>(); 
    } 

    public void Add(int id) 
    { 
     IUserRepository repo = factory.Create(new TestContext()); 

     this.users.Add(repo.Get(id)); 
    } 

    public int Count { get { return this.users.Count; } } 
} 

在實踐中,緩存讀通過,並填寫自己使用一個UserRepository用戶實體(和相關IUserRepository接口) :

public class UserRepository : IUserRepository 
{ 
    private readonly TestContext context; 

    public UserRepository(TestContext context) 
    { 
     this.context = context; 
    } 

    public User Get(int id) 
    { 
     return new User() { Name = "Test User" }; 
    } 
} 

緩存是長期存在的並且在整個應用程序中共享。我的問題是這樣的:我想用我的UserRepository從我的數據庫中拉用戶實體。該存儲庫需要以某種方式注入緩存中,或者使用工廠實例化。

訣竅是,我已經能夠創建緩存的唯一方式,Ninject將注入它的依賴關係,並且b)可以在整個緩存中訪問緩存,注射到需要訪問它的對象:

kernel.Bind<TestContext>().ToSelf(); 
kernel.Bind<UserCache>().ToSelf().InSingletonScope(); 

...然後在控制器(例如):

[Inject] 
public UserCache Cache { get; set; } 

我的問題是,這是長期治療的最佳方法需要注射的生物體?還是有更好的方法,我錯過了?我不想讓緩存(或任何其他類似的對象)直接訪問Ninject內核。

+0

這不起作用。任何這樣的對象都必須完全線程安全。 – SLaks

+0

實際上,這將是線程安全的。上面的代碼只是我用來了解Ninject應該如何工作的臨時項目的一些示例。 –

回答

5

這不應該是其他方式?你應該在你的控制器中使用IUserRepository,並且如果已經緩存了,那麼引擎蓋下的存儲庫應該從緩存中獲取數據(如果使用攔截器,則更好),否則應該訪問數據庫。

這樣你就不必擔心長生存緩存對象的生命週期。請記住,在一天結束時,整個WebAPI(至今)都運行在Web棧上,這意味着應用程序可以根據不同的因素意外回收。

+1

男人,很簡單!我認爲,也許我迷失在試圖讓事物分離,並且無法看到樹木的森林。 –