Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static initialization BEFORE main

I have a piece of software where there is a central abstract Factory method responsible for opening files. At first, the factory knew about all the file-types it can open and the corresponding objects it creates (every file-type has a different handler), but as time grew it became impractical: firstly, it was undesirable to fiddle with the factory class when handling new file-types; secondly, some of the concrete file handlers existed in separate DLLs, making them inaccessible from the factory! (The file handlers sometimes require the factory to handle files who only index paths to other files, therefore they must know the factory; if the factory knew them, the dependency would be cyclic)

The solution we came up with is for every new object type to 'register' itself with the factory, so that once the factory method is created, it will test the registered object types to see which one is the most suitable one and create it.

The largest problem is: when do these objects register themselves to the factory? Ideally, it would happen once before any call to the factory. However, since in C# you can't count on static c'tors to be called before accessing the type, I don't know how this can be done. Our current solution is to perform a dll-wide Initialize method which registers the object types with the factory, but this is obviously a hack which I dislike.

Is there some design pattern we're missing? A different way to handle this? It is important to note that the file handlers which need to register to the factory are in separate DLLs which MUST reference the factory.

like image 861
Gilthans Avatar asked Jul 14 '26 14:07

Gilthans


1 Answers

It seems that you have some problems with design of your application. There is some techniques to brake cyclic dependencies like yours. Usually programmers use inversion of control for this. In this case you can use in your "factory" class interface of handler instead of concrete realization. Interface should be defined in same dll with factory or in another "core" dll, that will be referenced from both your dlls.

like image 77
Kirill Bestemyanov Avatar answered Jul 16 '26 05:07

Kirill Bestemyanov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!