Search code examples
inversion-of-controldryioc

Cannot register non-concrete services with WithConcreteTypeDynamicRegistrations() as rules in DryIoc


Apparently I am trying to register an interface however, it seems like I cannot register it with non-concrete service below is an example of the implementation

interface IClassA
{
    void Students(List<string> students);
}

class School
{
    public School(IClassA classA)
    {
    }
}
class Program
{
    public static Rules DefaultRules => Rules.Default.WithConcreteTypeDynamicRegistrations()
                                                         .With(Made.Of(FactoryMethod.ConstructorWithResolvableArguments))
                                                         .WithFuncAndLazyWithoutRegistration()
                                                         .WithTrackingDisposableTransients()
                                                         .WithoutFastExpressionCompiler()
                                                         .WithDefaultIfAlreadyRegistered(IfAlreadyRegistered.Replace)
    static void Main(string[] args)
    {
        var container = new Container(DefaultRules);
        //this throws
        container.Register<IClassA>();

    }
}

Below is the error exception:

DryIoc.ContainerException: code: RegisteringAbstractImplementationTypeAndNoFactoryMethod; message: Registering abstract implementation type IClassA when it is should be concrete


Solution

  • You need to register the concrete implementation for IClassA interface because the container requires something concrete to instantiate.

    The rule WithConcreteTypeDynamicRegistrations is for concrete implementation dependencies (for class and not for interface), so you don't need to register them at all. Like this:

    class School
    {
        public School(MyClassA classA)
        {
        }
    }
    
    public static class Program 
    {
        static void Main(string[] args)
        {
            var container = new Container(DefaultRules);
            // it works even without registering School and MyClassA
            container.Register<School>();
        }
    }