Spring4d.Container - where to declare what?

Spring4d.Container - where to declare what?

Let's say I have 2 units:

myInterfaces.pas
myClasses.pas

it is straightforward to have a myRegister.pas which uses those and register the types with the GlobalContainer.

Now, if I need a class factory where do I put that declaration? My inclination is to put it with the classes, but that means you would need to place myClasses in the uses clause in the unit that is using the interface - which is not what we want as that binds the application to the class. I have been putting them in myInterfaces.pas - which is fine if the implementations of the interfaces use the same constructor.

So what's the mood around this?

Comments

  1. I would do this:

    1. Put interfaces in their own units. Those units should have nothing but interfaces in them. No code at all.
    2. Use Constructor Injection as much as you can. Use Property Injection for optional dependencies.
    3. Create and use your own container.. Don't use the Global Container.
    4. Put all your container registrations into a single unit. That will be the only place that you couple your code to your interfaces.
    5. Make a single call to Resolve in the root of your application (Preferably in your DPR file) and let constructor injection do the rest.

    ReplyDelete
  2. Thanks, Nick, so basically avoid factories?. Out of interest, w
    hat is the reason for not using the Global Container?

    ReplyDelete
  3. I don't see a need for factories if you are going to use a container.

    Don't use the Global Container because it's a global variable. ;-)

    ReplyDelete
  4. Re. why we should prefer Constructor Injection as Nick suggested, my understanding is that it's very clear (as opposed to other injection patterns such as Field Injection) to see the dependencies just by looking at the class's constructor, because the constructor is the *only entry point* of external dependencies flowing into the class.

    ReplyDelete
  5. The only reason I had for the factory is I am refactoring some classes and the constructors require passing either some primitive types or already resolved interfaces

    ReplyDelete
  6. Nick Hodges how about updating the fileviewer app to illustrate these points?

    ReplyDelete

Post a Comment