2011-11-24 95 views
2

我目前使用的爲metadata附上緩存模式上像這樣綁定到資源庫基於環境條件結合:ninject結合爲metadata確定

Bind<IRepo>().To<CachedRepo>().WithMetaData(MetadataKeys.RepoKey, CacheMode.Cached); 
Bind<IRepo>().To<Repo>().WithMetaData(MetadataKeys.RepoKey, CacheMode.NotCached); 

static CacheMode GetTheCurrentCacheMode() 
{ 
    //returns a CacheMode based on some environmental settings 
} 

statuc Func<IBindingMetadata, bool> BasedOnTheCurrentCachingModeforTheRequest() 
{ 
    return meta => meta.Has(MetadataKeys.RepoKey) 
        meta.Get<CacheMode>(MetadataKeys.RepoKey) == GetTheCurrentCacheMode(); 
} 

有沒有更好的方式來做到這一點?目前,我有綁定調用類型的方法,這樣我就可以在ToMethod拉姆達搶具體IRepo:

Bind<TypeThatUsesTheIRepo>.ToMethod(context => context.Kernel.Get<IRepo>(BasedOnTheCurrentCachingModeforTheRequest)); 

我個人不介意的解決方案,但我不能完全肯定它的最好的選項,給我想要實現的(在運行時根據環境選擇不同的IRepo實現)。

回答

3

在這種情況下,最好是使用這樣的條件:

Bind<IRepo>().To<CachedRepo>().When(_ => GetTheCurrentCacheMode() == CacheMode.Cached); 
Bind<IRepo>().To<Repo>().When(_ => GetTheCurrentCacheMode() == CacheMode.NotCached); 

或添加一個擴展方法:

IBindingInNamedWithOrOnSyntax<T> WhenCachingModeIs<T>(
    this IBindingWhenSyntax<T> syntax, 
    CacheMode cacheMode) 
{ 
    return syntax.When(_ => GetTheCurrentCacheMode() == cacheMode); 
} 

Bind<IRepo>().To<CachedRepo>().WhenCachingModeIs(CacheMode.Cached); 
Bind<IRepo>().To<Repo>().WhenCachingModeIs(CacheMode.NotCached); 

另一種方法是使用相同的存儲庫實現並注入ICache成它。在不想緩存的情況下,注入緩存的Null實現,而不是真正的緩存。

+0

謝謝。我會試一試。我真的不喜歡有2個IRepo實現的想法,但它不是我的代碼。我只是在修理佈線。我喜歡你對ICache的想法。 – AaronHS