开发者

Ninject - Inject ModelState into Service?

开发者 https://www.devze.com 2023-02-16 02:56 出处:网络
I have a controller with a constructor like so: Public Sub New(Service As ICategoryService) The service\'s constructor looks like this:

I have a controller with a constructor like so:

Public Sub New(Service As ICategoryService)

The service's constructor looks like this:

Public Sub New(Repository As IRepository(Of Category), IValidationDictionary)

I have a class Named Mode开发者_如何学运维lStateWrapper that implements IValidationDictionary:

Public Class ModelStateWrapper
    Implements IValidationDictionary

    Private ModelState As ModelStateDictionary

    Public Sub New(ModelState As ModelStateDictionary)
        Me.ModelState = ModelState

    End Sub

    Public Sub AddError(Key As String, Message As String) Implements Core.Interfaces.IValidationDictionary.AddError
        ModelState.AddModelError(Key, Message)

    End Sub

    Public ReadOnly Property IsValid As Boolean Implements Core.Interfaces.IValidationDictionary.IsValid
        Get
            Return ModelState.IsValid
        End Get
    End Property

End Class

I want to inject the ModelState of the controller into the ModelStateWrapper, and inject that into the service. Is this possible?

I have looked at custom providers in Ninject, and have the controllers inherit a BaseController class, but it does not seem to work. Any ideas?

Also, what is the standard way to do validation in the service layer that can be used from the controller?


It seems like you would have a problem trying inject ModelState because of the fact that once in an action method you already have the instance of ModelState that you want to pass into your wrapper.

Not every single object needs to or should be injected. Sometimes, this case potentially being one of those times, it is cleaner and easier and simpler to "inject" or provide the dependency or object as a parameter to the method that requires it. That is, pass IValidationDictionary as a parameter to the methods in your Service. Construct a ModelStateWrapper in the controller (new it up or use a Factory), and pass it in.

0

精彩评论

暂无评论...
验证码 换一张
取 消