Spring4D - named registrations do not call constructor?

Spring4D - named registrations do not call constructor? 

I have an ICommandHandler interface, with multiple implementations and I'm registering then with the container using names :

 container.RegisterType('command.help');
 container.RegisterType('command.another');

I'm calling contaner.Resolve(commandName) in my factory class, and this does return the correct instance, but never calls the constructor exposed on the class (each one has a different constructor).

Should this work or am I missing something?  Stefan Glienke

Comments

  1. IIRC the Container calls the first constructor that is found on which all dependencies can be satisfied.
    In your case, it looks like it is the default TObject constructor.

    Try adding [Inject] attributes to the constructor parameters on one of your classes for testing purposes, if the container can't find a dependency it should complain about it.

    ** EDIT **
    Scratch that, I did not get it to complain about missing dependencies.
    Nevertheless, this will be your problem: The container can't resolve a dependency for a constructor and will not call it.

    ** EDIT 2 **
    And another edit, now I got it to complain: Add [Inject] above the constructor.
    http://pastebin.com/HUuYdkJY

    ReplyDelete
  2. Martin Wienold thanks.. with [Inject] I get the exception and was able to figure out the dependency problem, without it I get an av. 
    Edit.. not sure what I changed, before it would just call the default constructor, now it av's.. at least with the attribute I could figure out that I forgot to register something.

    ReplyDelete
  3. Ok, working now without the Inject attribute, just needed to fix up some other dependencies. I had defined the interfaces for a whole bunch of dependencies but hadn't actually implemented all of them ;) Strange that it just called the TObject constructor before.

    ReplyDelete
  4. The default behavior of the container is to look for the ctor with the most arguments that it can inject all. Unfortunately via RTTI it always finds the TObject ctor which it then can call.
    But the container behavior can easily be modified via extensions - there is one that comes with the library in Spring.Container.ActivatorExtension.pas

    You can simply add it by calling container.AddExtension;
    This will change the behavior of the container to look for the ctor with the most arguments and if that one cannot be satisfied raises an EResolveException.

    ReplyDelete
  5. Ok thanks.. will give that a try next time.

    ReplyDelete

Post a Comment