Skip to main content

CastleWindsor issue with MVC Area

I have been stuck with this issue and couldn't take it out of my head. Hence, ended up putting in some heavy hours solving it. But hopefully it is worth it.

THE CONTEXT:

I am implementing a MVC solution for an existing Sitecore 8.0 implementation which uses Castle Windsor for it's dependency resolver. Let's say a a tiny microsite. I had to implement a SPEAK app as per one of the requirements. Below are the 2 most important things behind why I ran into this issue in the first place:

I needed to call a WebApi from my SPEAK app.
2. I decided to take MVC Area approach for my "tiny microsite" on a completely different sets of dlls

For example the dlls for my "tiny microsite" are MyTinyApp.Web.dll, MyTinyApp.Business.dll whereas the main website's dlls are BigWebsite.Web.dll, BigWebsite.Business.dll etc. 


WHY MVC AREA:

The reason I took the MVC Area approach was to completely separate my "tiny microsite" so that I don't have to touch any of the code from "BigWebsite" implementation (Or it can also be that the code base for the "Big Website" was unavailable to me .. imagine whatever floats your boat).


THE PROBLEM:

After I implemented my MVC Area project on dll called "MyTinyApp.Web.dll" for my "tiny microsite) upon trying to call the WebApi I started getting bellow error:



From the error it's clear that the routing got resolved without any issue. But Castle Windsor for some weird reason decided to step in like "hai .. new controller .. i need to resolve this" which I would be cool with until it couldn't and threw the bizarre error that doen't make sense to begin with. 

I have never told Castle Windsor to resolve any of my stuff for "MyTinyApp.Web.dll" and the exception was getting thrown from BigWebsite.Web.dll. 

WEIRD.


THE SOLUTION:

1. Create a processor in one of your project specific config file like below:


<pipelines>
      <initialize>
                               <processor patch:before="processor[@type='Sitecore.Mvc.Pipelines.Loader.InitializeGlobalFilters, Sitecore.Mvc']" type="MyTinyApp.CastleWindsor.Pipelines.Initialize.InitializeWindsorControllerFactory, MyTinyApp.CastleWindsor" />
     </initialize>

 </pipelines>

2. Create a settings to get the assembly name associated with Big Website's dependency resolver.

  <setting name="BigWebsiteDependancyResolverAssembly" value="BigWebsite.Web.DependencyResolution.ContainerManager,BigWebsite.Web" />

3. Implement the ControllerFactory for TinyApp:


public class InitializeWindsorControllerFactory
    {
        public virtual void Process(PipelineArgs args)
        {
            string assemblyAndClass = ConfigHelper.GetValue("BigWebsiteDependancyResolverAssembly");
                Type resolverType = Type.GetType(assemblyAndClass);
                IWindsorContainer icontainer = (IWindsorContainer)(resolverType.GetProperty("Container").GetValue(null));

                icontainer.Register(Classes.FromAssemblyNamed("oblog.client.mvc").BasedOn<IController>().LifestyleTransient());
        }

    }

And waalaaa .. Double Rainbow and Unicorn,



The trick here was to get it through reflection.

Thus I do not have to touch the BigWebsite codebase at all so I can avoid deployment headache for it. Resolving though reflection makes it completely independent to any other dlls.  

"This is mainly intended for future me." but seriously CastleWindsor WTF !!!!



UPDATE:



So one of my genius colleagues figured out that original implementation of ControllerFactory in BigWebsite.Web project(csproj) had flaw in it. 

Here's his post:


So it was originally like below:

public class WindsorControllerFactory : DefaultControllerFactory
    {
        private readonly IKernel kernel;

        public WindsorControllerFactory(IKernel kernel)
        {
            this.kernel = kernel;
        }

        public override void ReleaseController(IController controller)
        {
            kernel.ReleaseComponent(controller);
        }

        protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
        {
            if (controllerType == null)
            {
                throw new HttpException(404, string.Format("The controller for path '{0}' could not be found.", requestContext.HttpContext.Request.Path));
            }

            return (IController)kernel.Resolve(controllerType);
        }

    }

Because of this line in the implementation of the ContainerManager class which you put in the initialize pipeline:
container.Install(FromAssembly.InDirectory(new AssemblyFilter(Path.GetDirectoryName(Uri.UnescapeDataString((new UriBuilder(Assembly.GetExecutingAssembly().CodeBase)).Path)), "BigWebsite*.dll")));
the described error was getting thrown from this line :  
return (IController)kernel.Resolve(controllerType);

Weirdly, most of the blog/tutorials show this example for implementing Castle Windsor for MVC.
The fix is to have this instead:
try
            {
                return (IController)kernel.Resolve(controllerType);
            }
            catch (Exception ex)
            {
                // do something
                return base.GetControllerInstance(requestContext, controllerType);

            }

And everything else works fine from here. No need to implement extra pipeline to inject you "mvc area" implementation dll into the pipeline or modify existing implementation.


Hope it helps someone facing the same issue save time so that he/she can utilize it properly to dress up like wookie.

  



Comments

Popular posts from this blog

Passwordless Auth to Azure Key Vault using External Secret and Workload Identity

I want to fetch my secrets from Azure KV and I don't want to use any password for it. Let's see how this can be implemented. This is yet another blog post (YABP) about ESO and Azure Workload Identity. Why Passwordless Auth: It is a common practice to use some sort of "master password" (spn clienid, clientsecret etc) to access Secret Vaults (in this case it is AZ KV) but that master password becomes a headache to manage (rotate, prevent leak etc). So, the passwordless auth to AKV is ideal.  Why ESO: This is discussed and addressed in the conclusion section. Workload Identity (Passwordless Auth): Lets make a backward start (just for a change). I will try to explain how the passwordless auth will work. This will make more sense when you will read through the detailed implementation section. Here's a sequence diagram to explain it: There's no magic here. This is a well documented process by microsoft  here . The below diagram (directly copied from the official doc...

Do you even Kubernetes ? - in private cloud

Kubernetes (“koo-burr-NET-eez”) /κυβερνήτης/ - Can be used as noun or verb. Noun "helmsman" or "pilot" or "Orchestrator". We use Kubernetes to achieve resiliency for our application. Verb Perform the act of doing Kubernetes. When done using TKG it is easy but can be super hard if the right tool is not used. Do you even Kubernetes? If I were to survey about how many people in IT industry (regardless of role) knows or at least heard about Kubernetes I would be very surprised if the percentage came out any less than at least 80%. I am curious though, How many people have actually deployed on Kubernetes? How many people have created a Kubernetes cluster? How? The answer could go either way of "Yeah, it's easy" OR "Dude!! it's hard". This is because, in my opinion, it all depends on choosing the right toolset that are fit for purpose. In this post I will create a Kubernetes cluster and deploy a microservice application End-To-End, th...

Openshift-Powered Homelab | Why, What, How

I wanted to build a Homelab for some time but it was taking a backseat as I always had access to cloud environments (eg: cloud accounts, VMware DC etc) and the use cases I was focusing on didn't really warrant for one. But lately, some new developments and opportunities in the industry triggered the need to explore use cases in a bare-metal server environment, ultimately leading to the built of my own homelab, called MetalSNO. In this post, I will discuss some of my key reasons for building a homelab, the goals I set for it, and the process I followed to building one from scratch. I'll conclude with some reflections on whether it was truly worth it and what I plan to do with it going forward. Compelling reasons (The Why ) My uses cases for a homelab weren't about hosting plex server, home automation etc (I have them on Raspberry PIs for some years now). My Homelab is really about exploring technologies and concepts that are on par with industry trend. Below are some of the ...

Managing devices using Edge Manager

Managing edge devices has been a complex process as traditional IT ops tools fall short in distributed, low-connectivity environment to manage huge quantity of devices.  Red Hat Edge Manager  (Open source project: FlightControl , GA'd by Red Hat on late Jan, 2026) solves these challenges by providing streamlined management of edge devices and applications through a declarative approach . Now, there's a fair bit to unpack here. But for simplicity this is how I am going to map those 3 things here: Management of edge devices: I am mapping this to LCM (including upgrade, patch etc) of the underlying OS (in this case RHEL OS of BootC flavor or at least UBI based RHEL ). Managing applications: Mapping this to deploying applications and LCM of the applications stack on the OS. Declarative approach: This one is super interesting. To me this is very K8s-yy but in the world of edge devices running linux (RHEL OS, as of today). And then this thing also has MCP : This is my next prob...

Smart wifi controlled irrigation system using Sonoff and Home Assistant on Raspberry Pi - Part 1

If you have a backyard just for the sake of having one or it came with the house and you hate watering your garden or lawn/backyard then you have come to the right place. I genuinely believe that it is a waste of my valuable time. I would rather watch bachelorette on TV than go outside, turn on tap, hold garden hose in hand to water. Too much work!! Luckily, we have things like sprinkler system, soaker etc which makes things a bit easy. But you still have to get off that comfy couch and turn on tap (then turn off if there's no tap timer in place). ** Skip to the youtube video part if reading is not your thing   When I first moved into my house at first it was exciting to get a backyard (decent size), but soon that turned on annoyance when it came down maintaining it, specially the watering part. I laid bunch sprinklers and soaker through out the yard and bought tap timer but I still needed to routinely turn on the tap timer. Eventually few days ago I had enough of this rub...

Cloud Native CICD or CICD Natively in Cloud

Kubernetes aka K8s is a popular term these days and the technology is reshaping how we develop, build and deliver applications for obvious good reasons. All the major cloud vendors have K8s offering as well as it is also available on onprem private clouds/data centres too ( Read my post about this ). Thus, I can claim that K8s as platform is cloud native and applications running on K8s are also cloud native (provided it meets some other criteria).  In this post I will describe my take on the topic Cloud Native CICD. Table of Contents: Cloud Native CI/CD CI, CD and Pipelines Challenges with Traditional CICD tools Core attributes of K8s native CICD tools Choices available for K8s native CICD tools Why I like Cartographer Cartographer drawbacks and solutions Mercator - The Cartographer UI Tanzu Application Platform Conclusion Cloud Native CI/CD: The term "Cloud Native CICD" can be interpreted in two ways: Produce cloud native deployable (through CI) and deploy/deliver it on a cl...