1

I have IDependency dependency, that is used in a huge amount of services. There are two implementations of this dependency: DefaultDependency and CustomDependency. DefaultDependency in most of services. CustomDependency should be used in small amount of services.

Code example that is not working because of several factories:

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

Is it possible to increase priority of scoped to factory for CustomDependency or something like that? Or the only way to achieve it is to register DefaultDependency as ScopedTo to all services that should use it?

Dotnet fiddle: https://dotnetfiddle.net/wPA19s

UPDATE:

I was able to make it work with FactoryMethod, but maybe there is some cleaner way:

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 with working resolving of CustomDependency: https://dotnetfiddle.net/Znps9L

Mickey P
  • 183
  • 1
  • 10
  • Make the constructors of those that require CustomDependency take a CustomDependency instead of IDependency. – Neil Mar 03 '21 at 15:56

2 Answers2

1

You may use the dependency condition from this answer https://stackoverflow.com/a/34613963/2492669

dadhi
  • 4,807
  • 19
  • 25
0

Make the constructors of those that require CustomDependency take a ICustomDependency instead of IDependency.

interface ICustomDependency : IDependency {}

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

class ThatRequiresCustomDependency
{
     public ThatRequiresCustomDependency(ICustomDependency cd) {}
}
Neil
  • 11,059
  • 3
  • 31
  • 56
  • I am restricted to such changes, as I mentioned initially this interface is in use in many other services, so I am not able to change it – Mickey P Mar 03 '21 at 16:10