加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – 使用Sharp Architecture注册自定义模型绑定器

发布时间:2020-12-16 07:27:36 所属栏目:asp.Net 来源:网络整理
导读:我是MVC(我使用的是ver.3)和Sharp Architecture的新手,我很难弄清楚如何使用自定义模型绑定器. 我有一个名为Teacher的域对象(不是视图模型),以及以标准Sharp Architecture方式完成的存储库ITeacherRepository.我注册这条路线: routes.MapRoute( "Teacher","
我是MVC(我使用的是ver.3)和Sharp Architecture的新手,我很难弄清楚如何使用自定义模型绑定器.

我有一个名为Teacher的域对象(不是视图模型),以及以标准Sharp Architecture方式完成的存储库ITeacherRepository.我注册这条路线:

routes.MapRoute(
            "Teacher","Teacher/{tid}/{action}",new { controller = "Teacher",action = "Index" });

而TeacherController上的Index方法如下所示:

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);
    }

一切正常.现在我想采取下一步,并为Teacher实现自定义模型绑定器,因此控制器方法可以如下所示:

public ActionResult Index(Teacher t)
    {
        if (t == null)
            throw new InvalidOperationException("No such teacher");

        TeacherDisplay display = new TeacherDisplay(t);
        return View("Index",display);
    }

我写了一个原始模型绑定器:

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;
    }
}

而现在我被卡住了.如何在Sharp Architecture项目中正确注册?我想我也必须将它插入Castle Windsor配置中.我是否应该有一个接口ITeacherBinder,并在温莎注册?

编辑

澄清我的问题:我无法弄清楚如何注册我的模型绑定器,以便MVC框架将通过Windsor实例化它,因此负责传递所需的构造函数参数.控制器由Windsor实例化,这在global.asax.cs中被这一行连接起来:

ControllerBuilder.Current.SetControllerFactory(new WindsorControllerFactory(container));

我没有看到一个等效的模型制造商工厂.

解决方法

注册的一种方法是在Global.asax中的Application_Start方法中添加以下行

ModelBinders.Binders.Add(typeof(Teacher),new TeacherModelBinder());

这http://www.dominicpettifer.co.uk/Blog/39/dependency-injection-in-asp-net-mvc-2—part-2–modelbinders-viewmodels描述了不同的方式.

要通过Castle Windsor,您可以将以下代码添加到ComponentRegistrar.cs(位于CastleWindsor文件夹中)

container.Register(AllTypes.Of()?????????.FromAssembly(typeof运算(TeacherBinder).Assembly)?????????.Configure(c => c.LifeStyle.Singleton.Named(???????????c.Implementation.Name.ToLower())));

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读