I described the “typed factory” concept here some days ago. The solution we looked at was requiring the Castle DynamicProxy dependency. If you want something simpler zero dependency and “just working” I creted a little hacking factory: AnyFactory. It is really simple and does not requires any external dependency, and can be integrated in your project by just adding a single file. I provided some documentation on the project wiki. The extension works by crafting a factory implementation using Reflection.Emit. It does not requires to configure anything since a unresolved dependency satisfying some restrictive rule is considered to be a factory, and the implementation is produced in the background.
the rules for an interface to be consider a factory are:
- It is a public interface
- Each method name starts with Create
- Each method return something
- There is no properties
The name is required to begin with Create, if it contains something after Create, this is considered to be a named binding to solve. Construction parameters can be specified, but there is a restriction: the parameter name should match the implementation constructor parameter name. ANother limitation is that we don’t support the “delegate” factory.