Use in projects Castle IOC Container, Asp.net ProgramHow to get Castle Container.
It can be implemented as follows:
1 , gloabal Implementation interface icontaineraccessor
Public ClassGlobal: system. Web. httpapplication, icontaineraccessor
{
/// <Summary>
///Required designer variables.
/// </Summary>
PrivateSystem. componentmodel. icontainer components =Null;
Private StaticWindsorcontainer container;
PublicGlobal ()
{
Initializecomponent ();
}
Protected VoidApplication_start (Object sender, eventargs E)
{
Container =NewMycontainer (NewXmlinterpreter ("app_config.xml "));
}
Protected VoidSession_start (Object sender, eventargs E)
{
}
......
Protected VoidApplication_end (Object sender, eventargs E)
{
Container. Dispose ();
}
# RegionIcontaineraccessor implementation
PublicIwindsorcontainer container
{
Get{ReturnContainer ;}
}
}
2. Use the following class to obtain the container instance.CodeFrom Castle. MVC
/// <Summary>
///Uses the httpcontext and<See CREF = "icontaineraccessor"/>
///To access the container instance.
/// </Summary>
Public AbstractClassContainerwebaccessorutil
{
/// <Summary>
///Get a container instance from Application
/// </Summary>
/// <Returns>Returns an iwindsorcontainer</Returns>
Public StaticIwindsorcontainer obtaincontainer ()
{
Icontaineraccessor containeraccessor =
Httpcontext. Current. applicationinstanceAsIcontaineraccessor;
If(Containeraccessor =Null)
{
Throw NewApplicationexception ("You must implement the interface in httpapplication Icontaineraccessor exposes container attributes " );
}
Iwindsorcontainer Container = containeraccessor. container;
If(Container =Null)
{
Throw NewApplicationexception ("httpapplication cannot get the container instance ");
}
ReturnContainer;
}
}
3. Use containerwebaccessorutil. obtaincontainer () to obtain the container instance in the post code of the specific user control and page. Of course, if you use Castle. MVC, the MVC framework is also used in this way, you should not be so troublesome, you can write this in the page and control base class.