在ASP.NET MVC应用程序中,我将接口实例作为参数传递。在下面的代码片段中,myinterface是接口实例。
return RedirectToAction( "Main", new RouteValueDictionary(
new { controller = controllerName, action = "Main", Id = Id, someInterface = myinterface } ) );
在收件人方面,操作如下:
public ActionResult Index(Int Id, ISomeInterface someInterface) {...}
我得到以下运行时异常:
无法创建界面实例
有没有办法做到这一点?
答案 0 :(得分:1)
我不知道你的理由是什么。我假设他们是有效的。 MVC不会为您的界面提供实现。您将必须覆盖默认的模型绑定行为,如下所示并提供具体类型(它可以来自您的IOC容器):
public class MyBinder : DefaultModelBinder
{
protected override object CreateModel(ControllerContext controllerContext
, ModelBindingContext bindingContext, Type modelType)
{
if (bindingContext.ModelType.Name == "ISomeInterface")
return new SomeType();
//You can get the concrete implementation from your IOC container
return base.CreateModel(controllerContext, bindingContext, modelType);
}
}
public interface ISomeInterface
{
string Val { get; set; }
}
public class SomeType : ISomeInterface
{
public string Val { get; set; }
}
然后在您的应用程序启动中将看起来如下所示:
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
ModelBinders.Binders.DefaultBinder = new MyBinder();
//Followed by other stuff
}
}
此处的工作
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
var routeValueDictionary = new RouteValueDictionary()
{
{"id",1},
{"Val","test"}
};
return RedirectToAction("Abouts", "Home", routeValueDictionary);
}
public ActionResult Abouts(int id, ISomeInterface testInterface)
{
ViewBag.Message = "Your application description page.";
return View();
}