1

我应该如何在我的自定义模型绑定器中正确实现数据访问?

就像在控制器中一样,我使用 IContentRepository,然后让它在构造函数中创建其实现类的实例。所以我已经准备好在稍后阶段合并 IoC (DI)。

现在我在模型活页夹中需要类似的东西。我需要在活页夹中进行一些数据库查找。我正在考虑像在控制器中那样做,但我愿意接受建议。

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

        public class WidgetZoneController : BaseController
        {
// BaseController has IContentRepository ContentRepository field
            public WidgetZoneController() : this(new XmlWidgetZoneRepository())
            {
            }

            public WidgetZoneController(IContentRepository repository)
            {
                ContentRepository = repository;
            }
    ...
4

2 回答 2

0

您可以对自定义模型绑定器类使用构造函数注入,也可以从 DefaultModelBinder 继承。

public class MyModelBinder : DefaultModelBinder
{
    IContentRepository ContentRepository;

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

使用自定义模型绑定器,您可以像这样在 Application_Start() 中注册它们:

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

现在在使用 IoC 时,您需要牢记对象的生命周期。当您将 IoC 与控制器一起使用时,它们存在于每个 Web 请求中。因此,如果您注入存储库,则任何数据连接或 OR/M 会话将仅存在那么短的时间。

使用模型绑定器,它基本上是一个长期存在的单例( Application_Start() )。因此,请确保您的存储库在这两种情况下都能正常工作。

于 2011-04-20T03:40:27.527 回答
0

因为活页夹通常绑定一个实体,所以您不需要像 那样的特定存储库IContentRepository,确实IRepository<T>可以很好地获取实体。

要实例化 IRipository,您可以使用类似的东西:

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

我建议您在这里查看实体绑定器的 CodeCampServer 实现:

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

于 2010-04-11T20:12:16.430 回答