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?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 bootstrapping 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:
- Where should I do Injection with Ninject 2+ (and how do I arrange my Modules?)
- Design - Where should objects be registered when using Windsor
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:
- Dependency Inject (DI) "friendly" library
- Replace Spring.Net IoC with another Container (e.g. Ninject)
As you may notice, these are general principles and apply to DI overall - not just to Unity.
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
精彩评论