WebUserControlComponentActivator
Attempts to dynamically load a UserControl by invoking Page.LoadControl. There are two uses of this class.
1) Add a component to the Kernel and add a VirtualPath attribute specifying the relative path of the .ascx file for the associated UserControl. (easy)
<component id="BasketView" service="Castle.ShoppingCart.IBasketView, Castle.ShoppingCart" type="Castle.ShoppingCart.BasketView, Castle.ShoppingCart" lifestyle="transient" virtualPath="~/Views/BasketView.ascx" />2) Precompile a UserControl and add the pre-compiled class to the Kernel. (hard) Has not been tested with proxies.
using Castle.Core;
using Castle.MicroKernel.Context;
using System;
using System.Web;
using System.Web.UI;
namespace Castle.MicroKernel.ComponentActivator
{
[Serializable]
public class WebUserControlComponentActivator : DefaultComponentActivator
{
public WebUserControlComponentActivator(ComponentModel model, IKernelInternal kernel, ComponentInstanceDelegate onCreation, ComponentInstanceDelegate onDestruction)
: base(model, kernel, onCreation, onDestruction)
{
}
protected override object CreateInstance(CreationContext context, ConstructorCandidate constructor, object[] arguments)
{
object obj = null;
Type implementation = base.Model.Implementation;
bool hasInterceptors = base.Model.HasInterceptors;
bool flag = true;
if (hasInterceptors)
flag = base.Kernel.ProxyFactory.RequiresTargetInstance(base.Kernel, base.Model);
if (flag)
try {
HttpContext current = HttpContext.get_Current();
if ((int)current == 0)
throw new InvalidOperationException("System.Web.HttpContext.Current is null. WebUserControlComponentActivator can only be used in an ASP.Net environment.");
Page val = current.get_Handler() as Page;
if (val == null)
throw new InvalidOperationException("System.Web.HttpContext.Current.Handler is not of type System.Web.UI.Page");
string text = base.Model.Configuration.Attributes["VirtualPath"];
obj = (string.IsNullOrEmpty(text) ? ((object)val.LoadControl(implementation, arguments)) : ((object)val.LoadControl(text)));
} catch (Exception innerException) {
throw new ComponentActivatorException("WebUserControlComponentActivator: could not instantiate " + base.Model.Implementation.FullName, innerException, base.Model);
}
if (hasInterceptors)
try {
return base.Kernel.ProxyFactory.Create(base.Kernel, obj, base.Model, context, arguments);
} catch (Exception innerException2) {
throw new ComponentActivatorException("ComponentActivator: could not proxy " + base.Model.Implementation.FullName, innerException2, base.Model);
}
return obj;
}
}
}