Car*_*ond 4 asp.net-mvc s#arp-architecture asp.net-mvc-3
我是MVC(我使用的是ver.3)和Sharp Architecture的新手,我很难弄清楚如何使用自定义模型绑定器.
我有一个名为的域对象(不是视图模型)Teacher,以及ITeacherRepository标准Sharp Architecture方式完成的存储库.我注册这条路线:
routes.MapRoute(
"Teacher",
"Teacher/{tid}/{action}",
new { controller = "Teacher", action = "Index" });
Run Code Online (Sandbox Code Playgroud)
和看起来像这样的Index方法TeacherController:
public ActionResult Index(int tid)
{
Teacher t = TeacherRepository.Get(tid);
if (t == null)
throw new InvalidOperationException("No such teacher");
TeacherDisplay display = new TeacherDisplay(t);
return View("Index", display);
}
Run Code Online (Sandbox Code Playgroud)
一切正常.现在我想采取下一步,并实现自定义模型绑定器,Teacher因此控制器方法可能如下所示:
public ActionResult Index(Teacher t)
{
if (t == null)
throw new InvalidOperationException("No such teacher");
TeacherDisplay display = new TeacherDisplay(t);
return View("Index", display);
}
Run Code Online (Sandbox Code Playgroud)
我写了一个原始模型绑定器:
public class TeacherBinder : SharpArch.Web.ModelBinder.SharpModelBinder
{
private ITeacherRepository teacherRepository = null;
public TeacherBinder(ITeacherRepository repo)
{
this.teacherRepository = repo;
}
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
int tid = (int)bindingContext.ValueProvider.GetValue("tid").ConvertTo(typeof(Int32));
Teacher t = teacherRepository.Get(tid);
return t;
}
}
Run Code Online (Sandbox Code Playgroud)
而现在我被卡住了.如何在Sharp Architecture项目中正确注册?我想我也必须将它插入Castle Windsor配置中.我是否应该有一个界面ITeacherBinder,并在温莎注册?
编辑
澄清我的问题:我无法弄清楚如何注册我的模型绑定器,以便MVC框架将通过Windsor实例化它,因此负责传递所需的构造函数参数.控制器由Windsor实例化,这一点被这一行连接起来global.asax.cs:
ControllerBuilder.Current.SetControllerFactory(new WindsorControllerFactory(container));
Run Code Online (Sandbox Code Playgroud)
我没有看到一个等效的模型制造商工厂.
hgi*_*ish 10
注册的一种方法是在Global.asax中的Application_Start方法中添加以下行
ModelBinders.Binders.Add(typeof(Teacher), new TeacherModelBinder());
Run Code Online (Sandbox Code Playgroud)
要通过Castle Windsor,您可以将以下代码添加到ComponentRegistrar.cs(位于CastleWindsor文件夹中)
container.Register(AllTypes.Of().FromAssembly(typeof(TeacherBinder).Assembly).Configure(c => c.LifeStyle.Singleton.Named(c.Implementation.Name.ToLower())));
| 归档时间: |
|
| 查看次数: |
3350 次 |
| 最近记录: |