views:

335

answers:

2

Hi,

I have some trouble implementing the Unity IOC into my project reading from config file.

Here is what I have

1) ClasslibraryA

2) ClasslibraryB that references ClasslibraryA

3) Winforms App that references ClasslibraryB

Note: SomeOther app will reference ClassLibraryA, eg. a web service.

ClasslibraryA will have to be configured for IOC depending on where it is used. eg. IDataSource will be different if it is called in the web service and when it is called from a local app.

ClasslibraryB will have its own set of dependencies as well to be injected by the main application, in this case, the winforms app. ClasslibraryB will instantiate many ClasslibraryA objects in a loop.

Winforms app will contain the concrete implementation of the ClassLibraryB's dependancies implementation and Container.Configure should be called here?

My questions are,

When and where do I call the Container.Configure in the application?
Do I need child container for all sub library tiers/layers?
Should classlibraryB or the winforms implement the concrete class for ClasslibraryA to be injected into classlibraryA? Should I group each layer/tier's IOC config into a different "Container" name in the config file?

A: 

you should call the Container.Configure at the very beginning of the app, but the ClassLibraryA should receive the dependency manually,perhaps having the WebMethod that is called insantiate the (or ask the ioc for an instance) right type

Francisco Noriega
A: 

Each application owns a separate container and is responsible for configuring that container instance. Configuration and the call to resolve should happen as close as possible to the application's entry point. This is called the Composition Root.

Your Windows Forms application should own, configure and resolve the container in its bootrapping code. That there might be other applications that also use ClassLibraryA is totally irrelevant to it.

The Web Service should own another container and configure it to suit its needs. It knows nothing about the Windows Forms application.

Here is more information about Composition Roots:

All the libraries should be completely DI Container-agnostic so that you can use any container (and any container instance) to wire up all the dependencies.

See here for more details:

As you may notice, these are general principles and apply to DI overall - not just to Unity.

Mark Seemann