I have a repository class with optional dependency:
class MyRepository : BaseRepository, IMyRepository
{
public MyRepository(IDataContext dataContext, IC
I've ended with implementing some sort of a NullObject pattern on my optional dependency:
public class NullCacheProvider : ICacheProvider
{
// …
}
And in the base repository class i have check:
public class BaseRepository
{
protected readonly ICacheProvider CacheProvider;
protected readonly bool ShouldUseCache;
protected BaseRepository(IDataContext context, ICacheProvider cacheProvider)
{
CacheProvider = cacheProvider;
ShouldUseCache =
CacheProvider != null && !(CacheProvider is NullCacheProvider);
}
}
Then in a projects where i don't need a cache i have configured Unity like this:
container
.RegisterType(new PerResolveLifetimeManager(), new InjectionConstructor())
.RegisterType()
.RegisterType();
The point of all this is that the particular repository may act differently depending on fact of existence the optional dependency. It may seem as some architectural flaw but the solution meets my requirements.