The following example demonstrates registering a named instance in Unity. The only problem here is that both the registration and resolving of the dependency is done using a string. Even using a static class to hardcode all strings in a kind-of type safe way gives us no guaranty that the developer will respect the convention.
An alternate way of doing this would be using a delegate to resolve the instance giving a type safe argument such as an enumeration. So the registration in unity is a bit different...
Instead of a static class with constants we now have a type safe enumeration:
...and finally the client class that resolves the delegate:
In addition the actual resolving of the configuration string (typically read from a config) is done lazy... at the moment we really need it.
Finally we don't have ambiguity in registering in the container a type such as string, since we now mark the instance with an additional type (marker type).
0 comments:
Post a Comment
Post a comment