1

我有一个用 .NET 4.5.2 上运行的 VB.NET 编写的 ASP.NET Web 窗体项目

我已经成功地将 Ninject 插入到我的应用程序中,但是我遇到了障碍。

我在我的网页中使用 Ninject 属性注入(示例如下)

Partial Class MyPage
    Inherits Page

<Inject>
Public Property _myService As IService

对这项工作的所有调用......所以这很好

_myService.DoWork()

但是,在我的应用程序中,我们有一个类用于将调用包装到我们的服务中(见下文)

Public Class MyWrapper

    <Inject>
    Public Property _myService As IService

    Public Sub DoWork()
        _myService.DoWork()
    End Sub

End Class

这个类被网页使用...

Dim wrapper As New MyWrapper()

wrapper.DoWork()

这不起作用 - 在 MyWrapper 类中,Ninject 没有注入 IService。

我猜是因为我的课程不是网页,它不在管道中,所以 Ninject 没有对它做任何事情。

我已经阅读了一些其他建议修改 MyWrapper 以从 Ninject.Web.PageBase 继承的帖子,但是尝试过它似乎不起作用。

有没有人有任何建议?

MyWrapper 在我们的应用程序中有 100 多个引用,因此理想情况下我不想更改每一行代码。

此外,MyWrapper 类有一些共享/静态方法——这会导致问题(如有必要,我可以更改它)。

仅供参考 - 上面的代码应该被视为伪代码 - 我是临时输入的而不是复制粘贴 - 所以它可能包含语法错误。

4

1 回答 1

0

终于搞定了。

所以,我无法让 MyWrapper 类使用 Ninject。我在这里的假设是,因为这是一个 Web 表单应用程序(而不是 MVC),所以管道是不同的,并且 MyWrapper 类没有通过相同的管道运行,因此 Ninject 永远不会意识到它。

这是我为“解决”我的问题所做的。

我创建了一个新的基本页面

Public Class MyBasePage
    Inherits System.Web.UI.Page

    <Inject>
    Public Property wrapper As MyWrapper
End Class

然后我将我的 .aspx.vb 页面(MyPage)更改为从上面继承...

Partial Class MyPage
    Inherits MyBasePage

我之前忘了提到我已将 MyWrapper 添加到 NinjectWebCommon.vb 文件中......

Private Shared Sub RegisterServices(kernel As IKernel)
    'The MappingModule is my external code where I Bind my interfaces to the concrete classes
    'So for the purpose of this example, the MappingModule resolves IService
    Dim mappingModule = New MappingModule()
    kernel.Load(mappingModule, loggingModule)

    'Because MyWrapper is a class within my web application (rather than an
    'external assembly which is handled in the above MappingModule) I have
    'to explicitly tell Ninject how to resolve it.
    kernel.Bind(Of MyWrapper).ToSelf().InRequestScope
End Sub

我编辑了 MyWrapper 类以包含一个新的成员变量和构造函数

private ReadOnly _service As IService

Public Sub New(service As IService)
    _service = service
End Sub

因此,有了上述内容,我现在可以使用我的网页 (MyPage.aspx.vb) 中的以下代码

wrapper.DoWork()

这现在有效。

作为健全性检查,我还在 IService 实现的 Constructor 和 Dispose 方法中添加了代码,并将其注销以查看对象的创建和处置时间。

从日志中,我可以看到我的 Service 对象已根据请求正确创建和处理。

于 2016-10-11T09:46:01.457 回答