Register null as instance in Unity container

前端 未结 5 1372
北恋
北恋 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:06

    For 'nice to have' dependencies you should use property injection instead of ctor injection. Config would look something like this:

    public class MyRepository
    {
      public ICacheProvider Cache { get; set; }
    }
    
    container.RegisterType(new InjectionProperty("Cache", typeof(ICacheProvider)));
    

    That would inject an implementation of ICacheProvider into a property named Cache of your MyRepository. As you would have to implement null checks wherever you make a call to the Cache property inside your repository class I would go with @dtryon's proposal and implement a NullCacheProvider. That is far more convenient and less error prone.

提交回复
热议问题