代码之家  ›  专栏  ›  技术社区  ›  mare

访问自定义模型绑定中的数据存储的正确方法是什么?

  •  1
  • mare  · 技术社区  · 15 年前

    如何在自定义模型绑定中正确实现数据访问?

    就像在控制器中一样,我使用IContentRepository,然后让它在构造函数中创建实现类的实例。因此,我已经准备好了一切,以便在稍后阶段将国际奥委会(DI)纳入其中。

    现在我需要一些类似的模型活页夹。我需要在活页夹里查数据库。我想用控制器的方法来做,但我愿意接受建议。

    这是我的一个控制器的一个片段,所以你可以想象我是如何在其中完成的:

            public class WidgetZoneController : BaseController
            {
    // BaseController has IContentRepository ContentRepository field
                public WidgetZoneController() : this(new XmlWidgetZoneRepository())
                {
                }
    
                public WidgetZoneController(IContentRepository repository)
                {
                    ContentRepository = repository;
                }
        ...
    
    2 回复  |  直到 15 年前
        1
  •  0
  •   Fitzchak Yitzchaki    15 年前

    因为绑定器通常绑定一个实体,所以您不需要像这样的特定存储库 IContentRepository 确实如此 IRepository<T> 得到实体会很好。

    var repositoryType = typeof (IRepository<>).MakeGenericType(entityType);
    

    我建议您看看entities binder的CodeCampServer实现,在这里:

    http://code.google.com/p/codecampserver/source/browse/trunk#trunk/src/UI/Binders/Entities

        2
  •  0
  •   Raul Nohea Goodness    14 年前

    可以将构造函数注入到自定义模型绑定器类中,也可以从DefaultModelBinder继承。

    public class MyModelBinder : DefaultModelBinder
    {
        IContentRepository ContentRepository;
    
        public MyModelBinder(IContentRepository contentRepository)
        {
            this.ContentRepository = contentRepository;
        }
    

    使用自定义模型绑定,可以在应用程序\u Start()中注册它们,如下所示:

    protected void Application_Start()
    {
        System.Web.Mvc.ModelBinders.Binders.Add(
               typeof(MyModel), new MyModelBinder(contentRepository)
        );
    

    对于模型绑定器,它基本上是一个长寿命的单例(Application\u Start())。因此,请确保您的存储库在这两种情况下都能正常工作。