I have some legacy code that is creating instances of classes.
I have managed to wire up an IOC container to scan assemblies and create instances of them. However, I have spotted that in a configuation class specific classes may be created numerous times.
The logic basically loops over an array of class types and if it matches the one a user selected it calls CreateInstance.
This is fine but the only way I can think to provide that functionality is to pass the IOC Container around and call Resolve which will provide a new instance of the class.
I know this is seriously frowned upon but I can’t think how to make it work.
Create an abstract factory which provides a layer of abstraction between the IOC container and the code requiring the new instances, this will avoid the code being littered with container dependent calls.
For example, when using the ‘Unity Application Block’,
Func<T>can be used as a factory. ThisFunc<T>then hides the container implementation which is actuallycontainer.Resolve<T>().Update
Here is an example: