-
Notifications
You must be signed in to change notification settings - Fork 2
Aliasing
Spring.NET IoC container bases on object ids. The Spring.FluentContext hides those literal ids and exposes methods like RegisterDefault() or RegisterUniquelyNamed() to register objects, which generate proper object ids behind the scene.
It works perfectly in most cases but becomes problematic when default object definition is referred in code using interface type, while it is registered as implementation.
The following example shows problem:
ctx.RegisterDefault<Window>();
IWindow window = ctx.GetObject<IWindow>(); //it expects definition like ctx.RegisterDefault<IWindow>();
Because generated id for interface type is different than generated id for implementation type, object will not be resolved.
It is possible to use RegisterNamed() method, however it requires usage of literals:
ctx.RegisterNamed<Window>("window");
IWindow window = ctx.GetObject<IWindow>("window");
The solution for this problem is to use RegisterDefaultAlias() method, that would create an alias for already defined object and make it available for both types:
ctx.RegisterDefault<Window>();
ctx.RegisterDefaultAlias<IWindow>().ToRegisteredDefault<Window>();
IWindow window = ctx.GetObject<IWindow>();
Aliasing functionality can be used in all cases when given definition suppose to be visible under multiple ids. Similarly to other features, there are methods like RegisterNamedAlias() and RegisterUniquelyNamedAlias() to work with ids and references, as well as ToRegistered() methods allowing to bind alias to definition referred by id or reference.
Continue reading: 14. AOP Proxy Factories