Factory Pattern

Apr 23, 2009 at 9:17 PM

Is there some kind of factory pattern you can substitute for a type in Unity?  You know, for instance, if I have an object taking a string in the constructor, it would be useful to configure that object to take a factory of string instead of a given string.

Something like a IFactory<string> which you could pass wherever you need a string and unity would call the IFactory<string>.Create().

It would basically be an indirection mechanism and would avoid setting values in the code or having multiple constructors.  It would make a lot of designs more elegant.

There was something like that in Spring.NET and was quite useful.


Apr 23, 2009 at 9:35 PM
Edited Apr 23, 2009 at 9:47 PM
Funny you should ask this as I've just posted a blog article about this very subject! You can find it here http://phazed.com/blog/unity-and-the-factory-method-pattern/.

If you don't want Unity to manage the lifetimes of the factory generated instances then you can use the StaticFactoryExtension. Check out David Hayden's example here http://davidhayden.com/blog/dave/archive/2009/02/08/UnityStaticFactoryExtensionRegisteringFactoryDelegateCreateObject.aspx.

Otherwise I think I'm right in saying you're going to have to look to a custom extension like the one I detail in my blog post. There maybe other examples out there, but I couldn't find any.

Apr 23, 2009 at 9:38 PM
Hi Dizzy,

Your text seems to have been weirdly encoded.  Any chance you could fix it?

Apr 23, 2009 at 9:43 PM
Sorry. It appears Firefox messed up the text. Teach me to use the beta! It should be fixed now.

Apr 23, 2009 at 9:49 PM
Great!  I'll have a read through that.  I think I should invest more time to understand the extension mechanism.