如何在 DryIoC 中正确注册服务的默认和作用域依赖项

How do I properly register default and scoped dependency for services in 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 到所有应该使用它的服务?

网络fiddle: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 fiddle 工作解析 CustomDependencyhttps://dotnetfiddle.net/Znps9L

使那些需要 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) {}
}

您可以使用此答案中的依赖条件