HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Are there side-effects to having a generic Ninject factory?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
genericaresideeffectshavingninjectfactorythere

Problem

Consider this class:

using Ninject;
using Ninject.Syntax;
using Ninject.Parameters;

namespace MyApp.Dependencies.Factories
{
    public abstract class FactoryBase where T : class
    {
        private IResolutionRoot _resolutionRoot;
        protected FactoryBase(IResolutionRoot resolutionRoot)
        {
            _resolutionRoot = resolutionRoot;
        }

        protected T Create(params IParameter[] parameters)
        {
            return _resolutionRoot.Get(parameters);
        }
    }
}


What this class really abstracts away, is the _resolutionRoot.Get 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, 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?

Solution

Line-by-line I had exactly the same factory code. It smells, isn't it?

The correct solution would be to use Ninject Factory extension. I am happy since.

Context

StackExchange Code Review Q#25038, answer score: 3

Revisions (0)

No revisions yet.