注册null作为实例,在Unity容器容器、实例、null、Unity

2023-09-03 04:51:12 作者:我的心里没有人

我有一个可选的依赖的资源库类:

I have a repository class with optional dependency:

class MyRepository : BaseRepository, IMyRepository
{
    public MyRepository(IDataContext dataContext, ICacheProvider cacheProvider = null)
        : base(dataContext, cacheProvider)
    {}

    // …
}

中的cacheProvider参数作为战略储备库的存在。 我想这样的设置统一的容器:

The existence of cacheProvider parameter acts as strategy for the repository. I want setup Unity container like this:

Container.RegisterType<IDataContext, MyDataContext>(new PerResolveLifetimeManager(), new InjectionConstructor())
         .RegisterInstance<ICacheProvider>(null) // ???
         .RegisterType<IMyRepository, MyRepository>();

即。没有指出特定的InjectionConstructor一个参数MyRepository,但使用默认构造函数,使用null作为的的cacheProvider 的参数。

有没有办法做到这一点?

Is there any way to do this?

推荐答案

.RegisterType&LT; IMyRepository,MyRepository&GT;()调用,指定InjectionConstructor与OptionalParameter,在

.RegisterType<IMyRepository, MyRepository>(new InjectionConstructor(
new ResolvedParameter<IDataContext>(), 
new OptionalParameter<ICacheProvider>()));