Configuring a Factory with Unity
I've just started using Unity (v1.2) and in one scenario I need to be able to configure Unity with a factory for a type, rather than default to Unity creating an object of the type configured for the requested type. In my case the object implementing the interface is a Remoting proxy but say, for example, I have interface IFoo implemented by class Foo and I want instances of IFoo returned by Unity to be instances of Foo created by a factory class:
interface IFoo
{
void DoFoo();
}
class Foo : IFoo
{
public void DoFoo()
{
Console.WriteLine("DoFoo: CreatedBy = {0}", CreatedBy);
}
public string CreatedBy { get; set; }
}
class FooFactory
{
static public IFoo CreateInstance()
{
Console.WriteLine("CreateInstance");
var foo = new Foo();
foo.CreatedBy = "Factory";
return foo;
}
}
The solution is to use Unity's StaticFactoryExtension. After creating the container, add the extension to the container and then register the factory:
using Microsoft.Practices.Unity; using Microsoft.Practices.Unity.StaticFactory; // ... IUnityContainer container = new UnityContainer(); container.AddNewExtension<StaticFactoryExtension>(); IStaticFactoryConfiguration config = container.Configure<IStaticFactoryConfiguration>(); config.RegisterFactory<IFoo>(unity => FooFactory.CreateInstance());
Finally we can request an instance of IFoo from the container:
IFoo foo = container.Resolve<IFoo>(); foo.DoFoo();
The following assembly references are required:
- Microsoft.Practices.ObjectBuilder2
- Microsoft.Practices.Unity
- Microsoft.Practices.Unity.StaticFactory
Posted by
Charles Cook
at 08:28 AM.
Permalink.
blog comments powered by Disqus.
Copyright © Charles Cook.