我正在ASP.NET MVC
使用Ninject
,我正在尝试创建一个ActionResult
工厂。假设我有以下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) { ... }
}
因此,对于每个ActionResult
,参数类型和参数数量将不同。我创建了一个ActionResultFactory
,如下所示:
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?
}
}
我如何编写工厂以便它可以获取参数并将它们传递给对象的构造函数?或者我应该这样做:
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";
其中每个属性是公开公开的,我在创建对象后分配它们?
答案 0 :(得分:1)
答案 1 :(得分:1)
创建3为每种类型创建一个方法,传递所需的参数并创建这样的实例。
public FailResult CreateFailResult(int failcode)
{
return _kernel.Get<FailResult>(new ConstructorArgument("failCode", failcode));
}
答案 2 :(得分: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;
}
}
答案 3 :(得分:0)
您可以为new up创建一个小提供程序并为您初始化ActionResult对象。在这里解释:
请参阅Creating an instance using Ninject with additional parameters in the constructor