0

第一次使用stackoverflow + ninject(IoC)

我有一种情况,我的业务对象以它们有模型的方式实现......即

Public Class Whatever
Implements IWhatEver
      Public Property Id as Integer
      Public Property Name as String

      Public Function SetWhatEver() as Whatever
           'Do Whatever Settings
      End Function
End Class

我正在使用 ninject 进行 DI(依赖注入)但是问题是我不能使用接口作为在动作中传递的模型,因此我正在尝试制作自定义模型绑定器并希望使用bindingContext.ModelType传递给 ninject 和ninject 为我解决它,所以我可以使用元数据进行绑定

Public Overrides Function BindModel(controllerContext As ControllerContext, bindingContext As ModelBindingContext) As Object

        Dim modelType = ninjectPleaseResolve(bindingContext.ModelType)
        Dim metaData = ModelMetadataProviders.Current.GetMetadataForType(Nothing, modelType)

        bindingContext.ModelMetadata = metadata

    Return MyBase.BindModel(controllerContext, bindingContext)
End Function

我希望这是有道理的......我试图寻找答案顺便说一句,网上没有任何东西对我来说是有意义的,所以请你能简单地解释一下..

编辑

我在下面添加控制器代码,让您更好地理解我正在尝试做的事情。我不想使用 Whatever 类,而是想在控制器中使用 IWhatever 进行处理...请参阅下面是一个例子......

Public Class MainController
Inherits System.Web.Mvc.Controller

Dim repository As IWhatever

Public Sub New(pWhatever As IWhatever)
    repository = pWhatever
End Sub


Function Index(myValues As IWhatever) As ActionResult

      'So I can process these values to my liking...
      repository.SetWhatEver(myValues)

      ' and then perhaps other functions like...
      repository.Save()

      Return View()
End Function

我希望这现在有点意义..

4

1 回答 1

0

问题是我不能使用接口作为在动作中传递的模型

您不应该通过 action 方法传入服务。您应该通过构造函数传入服务。这样,您的容器可以为您构建控制器和所有相关对象,并且您不必编写自定义模型绑定器。

于 2013-08-15T07:10:45.073 回答