Factory method to construct the right implementation

50 views
Skip to first unread message

Mikael Syska

unread,
Feb 16, 2013, 12:01:20 PM2/16/13
to structure...@googlegroups.com
Hi,

I might be doing this the wrong way, so please feel free to suggest
other ideas. ( Lets just call it an idea that actually works )

I have two different Formatter, which is dependt on a url parameter.
So I wanted to create

interface IFactory<T>
{
T Get();
}

And an implementation:

public class Factory : IFactory<IFormater>
{
private readonly IWebManager _Manager;
private readonly Dictionary<Version, IFormater> _Formaters;

public Factory(IWebManager manager, IEnumerable<IFormater> formaters)
{
_Manager = manager;
_Formaters = formaters.ToDictionary(x => x.Version, x => x);
}

public IFormater Get()
{
var version = _Manager.GetSelectedServer().Version;

switch (version)
{
case Version.Version36:

case Version.Version40:
break;
default:
throw new ArgumentOutOfRangeException();
}

return _Formaters[version];
}
}

And the registration:
// To get the right implementation
For<IFormater>().HttpContextScoped().Use(x =>
x.GetInstance<IFactory<IFormater>>().Get());

// my formatters
For<IFormater>().HttpContextScoped().Add<FormaterImpl>();
For<IFormater>().HttpContextScoped().Add<Formater>();

// The factory registration:
For<IFactory<IFormater>>().HttpContextScoped().Use<Factory>();

This will ofcause not work ... since I now have a bi-directional dependency ...

I know I clould take a dependency on my IFactory<IFormatter> in my
classes ... but that's kind of a last solution I think.

How do people solve this? With the in class factory where I need an
IFormatter or?

I'm open to all suggestions, this is really killing me right now.

mvh
Reply all
Reply to author
Forward
0 new messages