模型中的ASP.NET MVC访问应用程序属性

时间:2008-12-15 16:25:39

标签: asp.net-mvc vb.net

我的global.asax看起来像这样

Imports Castle.Windsor
Imports Castle.Windsor.Configuration.Interpreters

Public Class MvcApplication
    Inherits System.Web.HttpApplication
    Implements IContainerAccessor

    Private Shared IoC As IWindsorContainer

    Shared Sub RegisterRoutes(ByVal routes As RouteCollection)
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}")

        ' MapRoute takes the following parameters, in order:
        ' (1) Route name
        ' (2) URL with parameters
        ' (3) Parameter defaults
        routes.MapRoute( _
            "Default", _
            "{controller}/{action}/{id}", _
            New With {.controller = "Home", .action = "Index", .id = ""} _
        )

    End Sub

    Sub Application_Start()
        RegisterRoutes(RouteTable.Routes)
        IoC = New WindsorContainer(New XmlInterpreter)
    End Sub

    Public ReadOnly Property Container() As Castle.Windsor.IWindsorContainer Implements Castle.Windsor.IContainerAccessor.Container
        Get
            Return IoC
        End Get
    End Property
End Class

如何从任何模型类中访问Container属性? 是否有一个我可以继承的类,它给了我视图中的“应用程序”属性,所以我可以这个

IoC = Application.Item(“Container”)......

1 个答案:

答案 0 :(得分:4)

您可能不希望模型对象知道您的IoC容器。

但是,为了回答你的问题,你可以像这样访问它:

(C#)

var container = ((IContainerAccessor)MvcApplication).Container;