在Unity容器中将null注册为实例
我有一个带可选依赖项的存储库类:
class MyRepository : BaseRepository, IMyRepository { public MyRepository(IDataContext dataContext, ICacheProvider cacheProvider = null) : base(dataContext, cacheProvider) {} // … }
cacheProvider参数的存在充当存储库的策略。 我想要像这样设置Unity容器:
Container.RegisterType(new PerResolveLifetimeManager(), new InjectionConstructor()) .RegisterInstance(null) // ??? .RegisterType();
也就是说没有为MyRepository指出具有一个参数的特定InjectionConstructor,而是使用带有null的默认构造函数作为cacheProvider参数。
有没有办法做到这一点?
在.RegisterType
调用中,使用OptionalParameter指定InjectionConstructor ,如
.RegisterType(new InjectionConstructor( new ResolvedParameter(), new OptionalParameter()));
我发现RegisterType而不是Register实例支持返回null。
container.RegisterType(new InjectionFactory((c) => null));
这是获得返回实际null
的最直接方法。
对于“很好拥有”依赖关系,你应该使用属性注入而不是ctor注入。 Config看起来像这样:
public class MyRepository { public ICacheProvider Cache { get; set; } } container.RegisterType(new InjectionProperty("Cache", typeof(ICacheProvider)));
这会将ICacheProvider
的实现注入到MyRepository
名为Cache
的属性MyRepository
。 由于您必须在存储库类中调用Cache
属性的任何地方实现空检查,我将使用@ dtryon的提议并实现NullCacheProvider
。 这样更方便,更不容易出错。
我结束了在可选依赖项上实现某种NullObject模式:
public class NullCacheProvider : ICacheProvider { // … }
在基础存储库类中,我检查:
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); } }
然后在我不需要缓存的项目中,我已经像这样配置了Unity:
container .RegisterType(new PerResolveLifetimeManager(), new InjectionConstructor()) .RegisterType() .RegisterType();
所有这一切的要点是,特定存储库可能根据存在的事实可选依赖性而采取不同的行为。 它可能看起来像一些架构缺陷,但解决方案符合我的要求。
上述就是C#学习教程:在Unity容器中将null注册为实例分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1014540.html