While writing a .NET based wizard engine I thought it would be fine to use an IoC container.
The concepts behind are pretty simple: Instead of creating an instance of a class, an IoC lets you specify explicit requirements in the form of interfaces (services) that are injected into a object instance before use. These services need to be registered and be available at the time of the instantiation.
There are a number of .NET IoC containers available. Scott Hanselman has collected a few.
Because I wanted a clear scope of the available services, I tried a thread local stack based approach to registering services. The using keyword is fine to get control over contexts that are bound to the current stack frame.
Another requirement was the direct injection into private fields, so that I don’t need to extend constructors to simply copy the arguments to private fields.
Attached is my first approach that I implemented this morning:
To register a service interface, use:
using (ServiceLocator.register<InterfaceType>(implementation)) { <code that may construct objects depending on InterfaceType> }
To specify a dependency:
class ClassThatRequiresAService { [Inject] ISomeInterface myServiceDependency_; }
To instantiate the class above, use:
ServiceLocator.create<ClassThatRequiresAService>();
Attached are the source files, the license is BSD. The source depends on DisposeAction.
yours
armin
| Attachment | Size |
|---|---|
| ServiceLocator.cs | 2.97 KB |
| Attributes.cs | 625 bytes |
Comments
Using injected services in the constructor.
... and if you need to use the injected services in your constructor, omit the Inject attribute:
yours
armin