I am currently using WithMetaData to attach a cache mode on a binding to a repository like so:
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();
}
Is there a better way to do this? Currently I have to bind the calling type to a method, so i can grab the specific IRepo in the ToMethod lambda:
Bind<TypeThatUsesTheIRepo>.ToMethod(context => context.Kernel.Get<IRepo>(BasedOnTheCurrentCachingModeforTheRequest));
I personally don't mind the solution, but I'm not entirely sure its the best option, given what I'm trying to achieve (a different IRepo implementation to be chosen at runtime based on the environment).
In this case it is better to use a condition like this:
Bind<IRepo>().To<CachedRepo>().When(_ => GetTheCurrentCacheMode() == CacheMode.Cached);
Bind<IRepo>().To<Repo>().When(_ => GetTheCurrentCacheMode() == CacheMode.NotCached);
or add a extension method:
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);
Another approach is to use the same repository implementation and inject ICache into it. In the case where you do not want to cache, inject a Null implementation of the cache instead of a real one.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With