C# ninject绑定,带元数据,用于根据环境条件确定绑定

C# ninject绑定,带元数据,用于根据环境条件确定绑定,c#,dependency-injection,ninject,C#,Dependency Injection,Ninject,我目前正在使用WithMetaData将绑定上的缓存模式附加到存储库,如下所示: Bind<IRepo>().To<CachedRepo>().WithMetaData(MetadataKeys.RepoKey, CacheMode.Cached); Bind<IRepo>().To<Repo>().WithMetaData(MetadataKeys.RepoKey, CacheMode.NotCached); static CacheMode

我目前正在使用WithMetaData将绑定上的缓存模式附加到存储库,如下所示:

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();
}
Bind().To().WithMetaData(MetadataKeys.RepoKey,CacheMode.Cached);
Bind().To().WithMetaData(MetadataKeys.RepoKey、CacheMode.NotCached);
静态缓存模式GetTheCurrentCacheMode()
{
//基于某些环境设置返回CacheMode
}
基于当前CachingModeforThereQuest()的状态函数
{
return meta=>meta.Has(MetadataKeys.RepoKey)
Get(MetadataKeys.RepoKey)==GetTheCurrentCacheMode();
}
有更好的方法吗?目前,我必须将调用类型绑定到一个方法,以便在ToMethod lambda中获取特定的IRepo:

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

我个人并不介意这个解决方案,但考虑到我正在努力实现的目标(在运行时根据环境选择不同的IRepo实现),我不完全确定这是最佳选择。

在这种情况下,最好使用如下条件:

Bind<IRepo>().To<CachedRepo>().When(_ => GetTheCurrentCacheMode() == CacheMode.Cached);
Bind<IRepo>().To<Repo>().When(_ => GetTheCurrentCacheMode() == CacheMode.NotCached);
Bind().To().When(=>GetTheCurrentCacheMode()==CacheMode.Cached);
Bind().To().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);
i当chingmode为(
此IBindingWhen语法,
缓存模式(缓存模式)
{
返回语法.When(=>GetTheCurrentCacheMode()==cacheMode);
}
Bind().To().WhenCachingModeIs(CacheMode.Cached);
Bind().To().WhenCachingModeIs(CacheMode.NotCached);

另一种方法是使用相同的存储库实现,并将
ICache
注入其中。如果不希望缓存,请插入缓存的实现,而不是真正的实现。

谢谢。我要试一试。我真的不喜欢有两个IRepo实现的想法,但这不是我的代码。我正在修电线。我喜欢你关于伊卡什的想法。