Castle Windsor Tutorial in Asp.Net MVC

Castle Windsor is one of the more popular IoC containers in the .NET space today. Others include StructureMap, NJect, AutoFac, Unity and others. My top choices are StructureMap and Castle, but I’ve never really used NJect or AutoFac and it’s my opinion that Unity is the weakest of them all and hardly worth mentioning. I’ll show some of the basics of Castle Windsor – enough to get you setup in your ASP.NET MVC, or any other .NET application. I’ll show you enough to handle 90%+ of the most common IoC needs. Much of my examples come from the S#arp Architecture, which I’m using in my current project.
Castle Windsor Configuration Options
Windsor offers 2 configuration options – .config file or code. Like many others, I have moved away from trying to do everything in my .config file and do more in code, practicing Convention or Configuration (CoC). Because the novelty of .config files is so early 2000′s, I’ll focus on configuring Castle using good ‘ole C# and some conventions I follow in my applications.
Common Conventions
Nothing ground breaking here, but I like to keep my controllers as light as possible. Therefore, I keep my application logic in an application service layer. My app services have one ore more repositories injected into them where domain objects can be retrieved for performing operations. My repositories, application services and interfaces all reside in different layers, which in my case is a physical assembly. Some folks prefer to inject repositories directly into the controller, which works as well, but using services works better for me because I feel I get better separation and it simplifies the controller’s constructor, which is how I handle dependency injection.
So here’s the breakdown of my layers (assemblies/projects):
Application Layer:
Application Services, Application Service Interfaces
Data Layer:
Repository Implementations
Domain Layer (Core):
Repository Interfaces
UI Layer:
Controllers
Configuring Castle to Handle My Conventions
All of my dependency injection is through the object’s constructor. As long as Windsor can resolve all the dependencies required by the constructors, it will be able to create and resolve the dependent objects as well. IoC configuration is typically left to the application (MVC, WinForms, WPF, etc.), so you would bootstrap the configuration in some sort of Application Start event, which in the case of ASP.NET is available from the Global.asax. All the code you’re about to see will exist in a class responsible for the IoC configuration that gets called from my Application_Start event.
First, a sample of a repository class and its interface, then how to automatically register all repositories in one swoop.
01//my repository class from the Data assembly
02namespace S2sol.Rpo.Data
03{
04 public class ClassroomRepository : S2sol.Rpo.Core.DataInterfaces.IClassroomRepository
05 {
06 }
07}
08
09//my Repository interface from the Core assembly
10namespace S2sol.Rpo.Core.DataInterfaces
11{
12 public interface IClassroomRepository
13 {
14 }
15}
16
17//this is how I would resolve an IClassroomRepository to its implementation from Castle
18IClassroomRepository repo = container.Resolve<IClassroomrepository>();

To make things simple, I’ll use Castle’s AllTypes.Pick() method, which effectively scans the types in an assembly. In my example below, I’m scanning my Data assembly and looking for non-generic interfaces that are the first interface defined on the classes in my Core assembly and register them with the container.
1private static void AddRepositoriesTo(IWindsorContainer container)
2{
3 container.Register(
4 AllTypes.Pick()
5 .FromAssembly(typeof(UserRepository).Assembly) //get the assembly where this repository lives
6 .WithService.FirstNonGenericCoreInterface("S2sol.Rpo.Core") //look for interfaces from this assembly
7 );
8}

I’m going to want to automatically register all my Application Services as well so they can be injected into my controllers. This syntax is a little simpler because those interfaces and implementations are in the same assembly.
1private static void AddApplicationServicesTo(IWindsorContainer container)
2{
3 container.Register(
4 AllTypes.Pick()
5 .FromAssembly(typeof(ProfileService).Assembly)
6 .WithService.FirstInterface());
7}

Now I’ll want to make sure that all my controllers are registered. This done by using the RegisterControllers extension method from the MvcContrib.Castle library.
1private static void AddControllersTo(IWindsorContainer container)
2{
3 container.RegisterControllers(typeof(HomeController).Assembly);
4}

Now all that’s left is to show the simple part, and that’s how to register any one-offs that may not fit into your conventions. For example, I have an IValidator interface that I want to resolve to the Validator implementation I’m using in this project.
1container.AddComponent<IValidator,Validator>();

It’s as simple as that. Once this has been put in place, I can just continue to develop repositories, application services, controllers and their respective interfaces and never have to remember to register any of them as long as I follow my conventions.
Castle’s Factory Facility
Facilities are how Castle handles extensibility. These are plugins for Castle that can be used for just about anything. Some of the more popular ones support NHibernate, WCF and logging. The one that comes in handy for my needs is the FactorySupportFacility. This facility allows me to configure a factory method in the container and control how objects get resolved.
The RoomParentsOnline MVC application makes use of a custom IPrincipal object that gets injected into my UserSession class, along with an HttpSessionStateBase implementation. The UserSession class is used for interacting with the current user, and by passing it an IPrincipal and HttpSessionStateBase, I have a testable design that I can develop using TDD.
1//constructor for the UserSession implementation
2public UserSession(IProfileService profileSerivce,
3 HttpSessionStateBase session, IPrincipal principal)

The first thing to do is make sure that Castle knows about the Factory Facility that I wish to use. To do this, you can either register the facility in the .config file or in code. I’ll show you how to add it in code. This would be done in your registrar class’s constructor to make sure it’s available right away.
1container.AddFacility<FactorySupportFacility>();

Now that Castle knows I’m using the Factory facility, I can tell it how I want to resolve the IPrincipal and HttpSessionStateBase. I also have to tell it how to resolve an IIdentity because of the way my code is accessing it (for testability). In the code below, I am telling Windsor to keep the registered objects available during the scope of a request. I then pass it the Function expression for how to create the object, which is all coming from the HttpContext.
01private static void AddSecurityConcernsTo(IWindsorContainer container)
02{
03 container.Register(Component.For<IIdentity>()
04 .LifeStyle.PerWebRequest
05 .UsingFactoryMethod(() => HttpContext.Current.User.Identity));
06
07 container.Register(Component.For<IPrincipal>()
08 .LifeStyle.PerWebRequest
09 .UsingFactoryMethod(() => HttpContext.Current.User));
10
11 container.Register(Component.For<HttpSessionStateBase>()
12 .LifeStyle.PerWebRequest
13 .UsingFactoryMethod(() => new HttpSessionStateWrapper(HttpContext.Current.Session)));
14
15
16}

I’m sure you’ll agree that this code makes it very simple to invert some of those pesky dependencies that come from the core ASP.NET plumbing. This technique is very effective for designing testable classes that need to interact with some of the “ugly stuff”.
The MvcContrib WindsorControllerFactory
Now that we have our Windsor container all configured to resolve our controllers, why not let the MVC framework use that container for creating our controllers. This can be done quite easily using the WindsorControllerFactory from the MvcContrib project. This is an implementation of ASP.NET MVC’s IControllerFactory interface. Using it is simple – just create an instance and give it your container and then register the factory with MVC. This is something that needs to be done during Application_Start.
1ControllerBuilder.Current.SetControllerFactory(new WindsorControllerFactory(container));

Common Service Locator
The last thing that I’ll mention is the CommonServiceLocator project. If you already have your IoC configured, you might as well make it available to all your code that may need to get object implementations without dependency injection. The CommonServiceLocator makes this easy by adapting all the major IoC containers to work under a common interface with a few key static methods. This is something that should also happen in the Application_Start.
1ServiceLocator.SetLocatorProvider(() => new WindsorServiceLocator(container));

Bringing it all Together
Now I’ll just put everything together for your copy/paste pleasure.
Global.asax
01protected void Application_Start()
02{
03 InitializeServiceLocator();
04
05 //do everything else here
06}
07
08/// <summary>
09/// Instantiate the container and add all Controllers that derive from
10/// WindsorController to the container. Also associate the Controller
11/// with the WindsorContainer ControllerFactory.
12/// </summary>
13protected virtual void InitializeServiceLocator()
14{
15 //create the container
16 IWindsorContainer container = new WindsorContainer();
17 //set the controller factory
18 ControllerBuilder.Current.SetControllerFactory(new WindsorControllerFactory(container));
19 //configure the container
20 ComponentRegistrar.AddComponentsTo(container);
21 //setup the common service locator
22 ServiceLocator.SetLocatorProvider(() => new WindsorServiceLocator(container));
23}

ComponentRegistrar.cs
01public class ComponentRegistrar
02 {
03 public static void AddComponentsTo(IWindsorContainer container)
04 {
05 container.AddFacility<FactorySupportFacility>();
06
07 AddControllersTo(container);
08 AddGenericRepositoriesTo(container);
09 AddCustomRepositoriesTo(container);
10 AddApplicationServicesTo(container);
11 AddOneOffs(container);
12 AddSecurityConcernsTo(container);
13 }
14
15 //add all my controllers
16 private static void AddControllersTo(IWindsorContainer container)
17 {
18 container.RegisterControllers(typeof(HomeController).Assembly);
19 }
20
21 //handle any one off registrations that aren't convention based
22 private static void AddOneOffs(IWindsorContainer container)
23 {
24 container.AddComponent<SharpArch.Core.CommonValidator.IValidator,Validator>("validator");
25 }
26
27 //handle registrations for my security classes
28 private static void AddSecurityConcernsTo(IWindsorContainer container)
29 {
30 container.Register(Component.For<IIdentity>()
31 .LifeStyle.PerWebRequest
32 .UsingFactoryMethod(() => HttpContext.Current.User.Identity));
33
34 container.Register(Component.For<IPrincipal>()
35 .LifeStyle.PerWebRequest
36 .UsingFactoryMethod(() => HttpContext.Current.User));
37
38 container.Register(Component.For<HttpSessionStateBase>()
39 .LifeStyle.PerWebRequest
40 .UsingFactoryMethod(() => new HttpSessionStateWrapper(HttpContext.Current.Session)));
41
42
43 }
44
45
46 //register my application services
47 private static void AddApplicationServicesTo(IWindsorContainer container)
48 {
49 container.Register(
50 AllTypes.Pick()
51 .FromAssembly(typeof(ProfileService).Assembly)
52 .WithService.FirstInterface());
53 }
54
55 //register all custom repositories (not generic)
56 private static void AddCustomRepositoriesTo(IWindsorContainer container)
57 {
58 container.Register(
59 AllTypes.Pick()
60 .FromAssembly(typeof(UserRepository).Assembly)
61 .WithService.FirstNonGenericCoreInterface("S2sol.Rpo.Core"));
62 }
63
64 //register all my SharpArch generic repos
65 private static void AddGenericRepositoriesTo(IWindsorContainer container)
66 {
67 container.AddComponent("entityDuplicateChecker",
68 typeof(IEntityDuplicateChecker), typeof(EntityDuplicateChecker));
69 container.AddComponent("repositoryType",
70 typeof(IRepository<>), typeof(Repository<>));
71 container.AddComponent("nhibernateRepositoryType",
72 typeof(INHibernateRepository<>), typeof(NHibernateRepository<>));
73 container.AddComponent("repositoryWithTypedId",
74 typeof(IRepositoryWithTypedId<,>), typeof(RepositoryWithTypedId<,>));
75 container.AddComponent("nhibernateRepositoryWithTypedId",
76 typeof(INHibernateRepositoryWithTypedId<,>), typeof(NHibernateRepositoryWithTypedId<,>));
77
78 }
79 }

Conclusion
This post ended up being longer than I originally intended, but hopefully you gleaned some nice little gems here. Castle Windsor is really easy to setup and use and there are many contributions out there that add more great functionality. Sometimes it’s hard to know how to use these types of tools without some concrete examples and I hope to have you shown you some useful ones here.

23 Responses to “Castle Windsor Tutorial in Asp.Net MVC”

  1. [...] to VoteCastle Windsor Tutorial in Asp.Net MVC (11/6/2009)Friday, November 06, 2009 from coreycooganCastle Windsor is one of the more popular IoC containers [...]
  2. oz said

    nice post.. just what I was looking for. Have a problem though: in the assemblies I have for Castle (1.1.0.5642), I cannot find the method FirstNonGenericCoreInterface(string). I can find the FirstInterface() but I need to specify the namespace for the interfaces, don’t I?
    Thanks
    • coreycoogan said

      Thanks oz, glad it provided some benefit to you. The FirstNonGenericCoreInterface method is actually an extension method from SharpArchitecture (see below). It’s open source, so I won’t bother adding the source here.
      As for the namespace, you don’t have to include it, but if you know where the interfaces should be, adding a filter will help. You can do that with the Where method:
      .Where(x => x.Namespace=="Com.YourNamespace")
      Here’s the metadata for the extension method:
      using Castle.MicroKernel.Registration;
      using System;
      using System.Runtime.CompilerServices;

      namespace SharpArch.Web.Castle
      {
      public static class WindsorExtensions
      {
      public static BasedOnDescriptor FirstNonGenericCoreInterface(this ServiceDescriptor descriptor, string interfaceNamespace);
      }
      }

  3. [...] First, a sample of a repository class and its interface, then how to automatically register all repositories in one swoop. view source [...]
  4. Hi Corey, Thanks for such a detailed and informative blog post. It really helped. I have referenced you in my current TDD and MVC series – http://scottfindlater.blogspot.com/2009/12/tdd-mvc-16-configuring-castle-windsor.html Thanks again. Scott.
  5. Joe Wilson said

    Thanks for putting this post together.
    I’m using Sharp Arch, too and was struggling with getting HttpSessionBase passed as HttpContext.Current.Session in my IoC registrations. The lines

    container.AddFacility();

    and

    UsingFactoryMethod(() => new HttpSessionStateWrapper(HttpContext.Current.Session)));

    were exactly what I needed.
  6. RT said

    Hi,
    Thank you for an excellent post.
    I’m new to .net-C#-MVC-web-Castle-Windsor development and have stumbled upon your post. I like the architecture you are using.
    You mentioned a couple of differences in your approach to the example on Sharp Architecture tutorial:
    1. Inject a service interface instead of injecting a repository interface into the controllers
    2. Use different assemblies instead of placing all the layers in a single assembly
    I was wondering whether it would be possible for you to elaborate on these (I know I’m asking for a lot) or point to resources that might help me make the transition.
    Thanks.
    • coreycoogan said

      Hi RT,
      first your number 1. Injecting an application service gives a couple distinct benefits over a repository.
      1. You can put your logic in the service and keep the controller focused on one thing – controlling flow.
      2. Often times operations require more than one repository. Let your app service handle this rather than injecting multiple repositories into your controller.
      As far as question 2 goes, there’s been much written and debated on this. I tried a separate assembly for my controllers and that was just plain hard to work with, so I moved those back to my UI layer. Separating Data/Services/Core creates a clear physical separation between my layers that can’t be breached. It enforces unilateral dependencies and is relatively easy to work with to me. Others, like Jeremy D. Miller, have stated that they prefer soft boundaries in the form of namespaces, so I’ll let you read the arguments and chose for yourself.
  7. Kevin said

    Can you post the code for this example?
    Where does UsingFactoryMethod come from?
    Is that from Sharp? (I’ve never used it before.. but I downloaded the code and didn’t find UsingFactoryMethod there)
    I guess there is where the trick of instantiating the Session object relies? Otherwise I don’t know how this works, since the Session object at the moment of the Application_Start gets triggered, is null.
    Can you explain this a bit further?
    Thanks.
    • Kevin said

      I’ll answer my own post: UsingFactoryMethod is part of Castle Windsor??… but WHERE? The latest I see is Windsor 2.0 – May 5th, 2009 , but it is not there.
      Thanks.
  8. Kevin said

    I was finally able to find that UsingFactoryMethod, but still this doesn’t work for me…
    I’m initializing my custom container in the Application_Start() event handler in the Global.asax.
    And my custom container looks this:
    public class MyContainer : WindsorContainer
    {
    public MyContainer() : base()
    {
    AddFacility();
    Register(Component.For()
    .LifeStyle.PerWebRequest
    .UsingFactoryMethod(() => new HttpSessionStateWrapper(HttpContext.Current.Session)));
    Initialize();
    }

    }
    But when the UsingFactoryMethod is called, the HttpContext.Current.Session is null.
    Additionally, this “.LifeStyle.PerWebRequest” doesn’t seem to work either.
    I’ve registered the PerWebRequest module but I always get:
    “Looks like you forgot to register the http module Castle.MicroKernel.Lifestyle.PerWebRequestLifestyleModule
    Add ” to the section on your web.config”
    Any idea of what is going on?
  9. coreycoogan said

    There is an issue with access the Container right away before the first request. I ran into this issue also while setting up some logging stuff right away. I had to post back first for the same reason. There’s some chatter about the issue and perhaps a solution by now.
    http://blog.alanta.nl/2009/07/castle-perwebrequestlifestyle-wont-work.html
  10. [...] blogged about Castle in the past, which I was using because it came standard in the S#arpArchitecture. Castle is a very [...]
  11. [...] diesem Post von Corey Coogan ist ein komplexeres Beispiel erläutert. Jedenfalls hat mir der Blogpost recht viel gebracht und [...]
  12. Resad said

    Very good post, thank you very much. Until now i have only used Unity but it seems that Castle.Windsor has some cool stuff to offer.
  13. sove said

    sove…
    [...]Castle Windsor Tutorial in Asp.Net MVC « Corey Coogan[...]…
  14. Vacances Aux Seychelles…
    [...]Castle Windsor Tutorial in Asp.Net MVC « Corey Coogan[...]…
  15. SushantK said

    Very nice article. I am currently playing around with the Windsor container in a layered architecture and your article does help a lot in breaking down the layers into specific projects. But I am having a quick question. Hew are the dependencies set for these layers. In my case, I have controller (web project) –>Entity (Interfaces), Service –> business (repository)
    But how would I configure the repository in the controller project if I do not have a reference to it.
    Thanks for your time.
    Sushant
    • coreycoogan said

      In your case, the controller should have references to your repository interfaces, which is typically in some .Data project that has NH mappings, repo interfaces, etc. Not sure about your web project referencing Entities by interfaces. Putting interfaces on your entities is generally considered an anti pattern.
      Hope this helps.
      • Sushant K said

        Thanks a lot for your response. here is how my project is structured–
        web Project (controller) — this creates the container and installs the components.
        |
        | references
        V
        Service Project — this has the Services (example UserService — login(), retirevepassword() etc.)
        entity Project — this has all the POCOS (EF mappings), Service, Repository Interfaces (IUserService etc.)
        |
        |
        V
        Repository Project — this has Repositories (UserRepository — GetUsers(), AddUser(), DeleteUser() etc.)
        entity Project — this has all the POCOS (EF mappings), Service, Repository Interfaces (IUserService, IuserRepository etc.)
        |
        |
        V
        Data project — This has the entity Framework Data Model
        Now, since my web project has reference to Service project and Entity project, I am able to install UserService into container, but since Service has IUserRepository dependency, it is unable to create it due to the fact that web project does not have reference to the Repository project. (even though the interfaces are all in the separate entity project).
        Any help would be highly appreciated.
        Thanks
      • coreycoogan said

        Your structure is a little different than I would typically use, but I think it’s probably just your naming convention. For example, I see no Domain project, so I’m guessing your EF project is your domain.
        Are you passing your entities directly to your web project or just using DTO’s? I would recommend looking at the Sharp Architecture project for a better idea of structuring dependencies.

Leave a Reply

Comments