如何在 DryIoC 中正确注册服务的默认和范围依赖项

问题描述

我有 IDependency 依赖项,用于大量服务。 此依赖项有两种实现:DefaultDependencyCustomDependencyDefaultDependency 在大多数服务中。 CustomDependency 应该用于少量服务。

由于多个工厂而无法工作的代码示例:

var container = new Container();

container.Register<IDependency,DefaultDependency>(Reuse.ScopedOrSingleton);
container.Register<IService,Service>(Reuse.ScopedOrSingleton,setup: Setup.With(openResolutionScope: true));
container.Register<IDependency,CustomDependency>(Reuse.ScopedTo<IService>());
        
var service = (Service)container.Resolve<IService>(); // Throws Error.ExpectedSingleDefaultFactory

是否可以为 CustomDependency 或类似的东西增加范围到工厂的优先级?或者实现它的唯一方法是将 DefaultDependency 注册为 ScopedTo 到所有应该使用它的服务?

Dotnet 小提琴:https://dotnetfiddle.net/wPA19s

更新:

我能够使用 FactoryMethod 使其工作,但也许有一些更简洁的方法

container.Register<CustomDependency>(Reuse.ScopedOrSingleton);
container.Register<IService,Service>(made: Made.Of(
    factoryMethod: r => FactoryMethod.Of(typeof(Service).GetConstructorOrNull(args: new[] { typeof(IDependency) })),parameters: Parameters.Of.Type<IDependency>(requiredServiceType: typeof(CustomDependency))));

Dotnet 处理 CustomDependency 的工作解析:https://dotnetfiddle.net/Znps9L

解决方法

您可以使用此答案中的依赖条件 https://stackoverflow.com/a/34613963/2492669

,

使那些需要 CustomDependency 的构造函数采用 ICustomDependency 而不是 IDependency

interface ICustomDependency : IDependency {}

container.Register<IDependency,DefaultDependency>(Reuse.ScopedOrSingleton);
container.Register<ICustomDependency,CustomDependency>(Reuse.ScopedTo<IService>());

class ThatRequiresCustomDependency
{
     public ThatRequiresCustomDependency(ICustomDependency cd) {}
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...