Sunday, March 6, 2011

ASP.NET MVC Access Application Property from Model

my global.asax looks like this

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

how do i access the Container property from within any Model Class? is there a class i can inherit from that gives me the "Application" property as in the view so i could to this

IoC = Application.Item("Container")...

From stackoverflow
  • You probably don't want your model objects knowing about your IoC container.

    But, for the sake of answering your question, you can access it like this:

    (C#)

    var container = ((IContainerAccessor)MvcApplication).Container;
    
    Paul : I want to agree 1000% that you don't want your model objects knowing about your IOC container. Everything they need from it should get passed to them when they get built.

0 comments:

Post a Comment