Consider this class:
using Ninject;
using Ninject.Syntax;
using Ninject.Parameters;
namespace MyApp.Dependencies.Factories
{
public abstract class FactoryBase<T> where T : class
{
private IResolutionRoot _resolutionRoot;
protected FactoryBase(IResolutionRoot resolutionRoot)
{
_resolutionRoot = resolutionRoot;
}
protected T Create(params IParameter[] parameters)
{
return _resolutionRoot.Get<T>(parameters);
}
}
}
What this class really abstracts away, is the _resolutionRoot.Get<T>
part, allowing for concrete factory classes to look something like this:
//using Ninject; // not needed
using Ninject.Syntax;
using Ninject.Parameters;
public interface IUnicornFactory
{
Unicorn Create(string name, int hornLength, Color color);
}
public class UnicornFactory : FactoryBase<Unicorn>, IUnicornFactory
{
public UnicornFactory(IResolutionRoot resolutionRoot)
: base(resolutionRoot)
{ }
public Unicorn Create(string name, int hornLength, Color color)
{
return Create(new ConstructorArgument("name", name),
new ConstructorArgument("hornLength", hornLength),
new ConstructorArgument("color", color));
}
}
Is this overkill, or something that I'll thank myself for later, when I have dozens of factory classes? I find the base factory merely allows for synctactic sugar in the concrete factory implementations - are there any side-effects to this?
dependency-injection
, but this is the right place to ask it. No experience with Ninject, so I can't answer, though. \$\endgroup\$ – Bobson Apr 12 '13 at 16:38IResolutionRoot
in the concrete factory implementation - I believe ReSharper (R#) would help here but as far as "good design practices" are concerned is it ok for an abstract class to require a constructor argument that the concrete implementation can't quite know about until compilation fails with a "[base class] does not contain a constructor that takes 0 arguments" error? VS doesn't give a "Implement abstract class" shortcut for the constructor... \$\endgroup\$ – Mathieu Guindon♦ Apr 12 '13 at 17:33