Search code examples
c#dependency-injectiondryioc

How do I properly register default and scoped dependency for services in DryIoC


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


Solution

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