1

I'm using ASP.NET MVC with Ninject and I'm trying to create an ActionResult factory. Let's say I have the following ActionResults:

public class SuccessResult : ActionResult
{
    public string SuccessMessage { get; set; }

    public SuccessResult(string successMessage) { ... }
}

public class FailResult : ActionResult
{
    public int FailCode { get; set; }

    public FailResult(int failCode) { ... }
}

public class DataResult : ActionResult
{
    public object Data { get; set; }
    public string MimeType { get; set; }

    public DataResult(object dataToSerialize, string mimeType) { ... }
}

So for each ActionResult, the parameter types and number of parameters will be different. I created an ActionResultFactory that looks like this:

public class ActionResultFactory
{
    private readonly IKernel _kernel;

    public ActionResultFactory(IKernel kernel)
    {
        _kernel = kernel;
    }

    public T Create<T>() where T : ActionResult
    {
        return _kernel.Get<T>(); // how do I pass the parameters?
    }
}

How would I write the factory so that it can take parameters and pass them to the object's constructor? Or should I do it like this instead:

var result = factory.Create<SuccessResult>();
result.SuccessMessage = "Success!";

var result = factory.Create<FailResult>();
result.FailCode = 404;

var result = factory.Create<DataResult>();
result.Data = file;
result.MimeType = "text/plain";

where each property is publically exposed and I assign them after object creation?

Daniel T.
  • 37,212
  • 36
  • 139
  • 206

4 Answers4

1

You need a Constructor injection with parameters.

Please see below link

Ninject with parameters

TalentTuner
  • 17,262
  • 5
  • 38
  • 63
1

Create 3 Create methods one for each type, pass the required arguments and create the instance like this.

public FailResult CreateFailResult(int failcode)
{
    return _kernel.Get<FailResult>(new ConstructorArgument("failCode", failcode));
}
Remo Gloor
  • 32,665
  • 4
  • 68
  • 98
0
public T Create<T>(params object[] parameters) 
{
    T instance = _kernel.Get<T>();
    if (typeof(T) == typeof(FailResult))
    {
        FailResult result = (FailResult)instance;
        result.ErrorCode = (int)parameters[0];
        return result;
    }
}
Jason Li
  • 1,528
  • 1
  • 12
  • 20
0

You could create a little provider to new up and initialize the ActionResult objects for you. Explained here:

See Creating an instance using Ninject with additional parameters in the constructor

Community
  • 1
  • 1