Register null as instance in Unity container

前端 未结 5 1361
北恋
北恋 2020-12-17 10:08

I have a repository class with optional dependency:

class MyRepository : BaseRepository, IMyRepository
{
    public MyRepository(IDataContext dataContext, IC         


        
5条回答
  •  醉梦人生
    2020-12-17 11:10

    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.

提交回复
热议问题