title: Castle Windsor IoC in an MVC application
body: <p>Prepare for a wall of code... It's a long read, but it's as verbose as I can get.</p>
  
  <p>In response to <a href="https://stackoverflow.com/questions/4390489/still-lost-on-repositories-and-decoupling-asp-net-mvc">Still lost on Repositories and Decoupling, ASP.NET MVC</a></p>
  
  <p>I <strong>think</strong> I am starting to get closer to understanding this all. 
  I'm trying to get used to using this. Here is what I have so far.</p>
  
  <h2>Project</h2>
  
  <blockquote>
    <p>Project.Web (ASP.NET MVC 3.0 RC)</p>
  </blockquote>
  
  <ul>
  <li>Uses Project.Models</li>
  <li>Uses Project.Persistence</li>
  </ul>
  
  <h2>Project</h2>
  
  <blockquote>
    <p>Project.Models (Domain Objects)</p>
  </blockquote>
  
  <ul>
  <li><code>Membership.Member</code></li>
  <li><code>Membership.IMembershipProvider</code></li>
  </ul>
  
  <h2>Project</h2>
  
  <blockquote>
    <p>Project.Persistence (Fluent nHibernate)</p>
  </blockquote>
  
  <ul>
  <li>Uses Project.Models</li>
  <li>Uses Castle.Core</li>
  <li><p>Uses Castle.Windsor</p></li>
  <li><p><code>Membership.MembershipProvider : IMembershipProvider</code></p></li>
  </ul>
  
  <p>I have the following class in <code>Project.Persistence</code></p>
  
  <pre><code>using Castle.Windsor;
  
  using Castle.MicroKernel.Registration;
  using Castle.MicroKernel.SubSystems.Configuration;
  
  namespace Project.Persistence
  {
      public static class IoC
      {
          private static IWindsorContainer _container;
  
          public static void Initialize()
          {
              _container = new WindsorContainer()
                  .Install(
                      new Persistence.Containers.Installers.RepositoryInstaller()
              );
          }
  
          public static T Resolve&lt;T&gt;()
          {
              return _container.Resolve&lt;T&gt;();
          }
      }
  }
  namespace Persistence.Containers.Installers
  {
      public class RepositoryInstaller : IWindsorInstaller
      {
          public void Install(IWindsorContainer container, IConfigurationStore store)
          {
              container.Register(
                  Component
                  .For&lt;Membership.IMembershipProvider&gt;()
                  .ImplementedBy&lt;Membership.MembershipProvider&gt;()
                  .LifeStyle.Singleton
              );
          }
      }
  }
  </code></pre>
  
  <p>Now, in <code>Project.Web</code> <code>Global.asax</code> <code>Application_Start</code>, I have the following code.</p>
  
  <pre><code>    protected void Application_Start()
      {
          AreaRegistration.RegisterAllAreas();
  
          RegisterGlobalFilters(GlobalFilters.Filters);
          RegisterRoutes(RouteTable.Routes);
  
          // Register the Windsor Container
          Project.Persistence.IoC.Initialize();
      }
  </code></pre>
  
  <p>Now then, in <code>Project.Web.Controllers.MembershipController</code> I have the following code.</p>
  
  <pre><code>    [HttpPost]
      public ActionResult Register( Web.Models.Authentication.Registration model)
      {
          if (ModelState.IsValid)
          {
              var provider = IoC.Resolve&lt;Membership.IMembershipProvider&gt;();
              provider.CreateUser(model.Email, model.Password);
          }
  
          // If we got this far, something failed, redisplay form
          return View(model);
      }
  </code></pre>
  
  <p>So I am asking first of all.. </p>
  
  <h2>Am I on the right track?</h2>
  
  <h2>How can I use Castle.Windsor for my ISessionFactory</h2>
  
  <p>I have my SessionFactory working like this ...</p>
  
  <pre><code>namespace Project.Persistence.Factories
  {
      public sealed class SessionFactoryContainer
      {
          private static readonly ISessionFactory _instance = CreateSessionFactory();
  
          static SessionFactoryContainer()
          { 
  
          }
  
          public static ISessionFactory Instance
          {
              get { return _instance; }
          }
  
          private static ISessionFactory CreateSessionFactory()
          {
              return Persistence.SessionFactory.Map(@"Data Source=.\SQLEXPRESS;Initial Catalog=FluentExample;Integrated Security=true", true);
          }
      }
  }
  namespace Project.Persistence
  {
      public static class SessionFactory
      {
          public static ISessionFactory Map(string connectionString, bool createSchema)
          {
              return FluentNHibernate.Cfg.Fluently.Configure()
                  .Database(FluentNHibernate.Cfg.Db.MsSqlConfiguration.MsSql2008
                      .ConnectionString(c =&gt; c.Is(connectionString)))
                      .ExposeConfiguration(config =&gt;
                      {
                          new NHibernate.Tool.hbm2ddl.SchemaExport(config)
                              .SetOutputFile("Output.sql")
                              .Create(/* Output to console */ false, /* Execute script against database */ createSchema);
                      })
                      .Mappings(m =&gt;
                      {
                          m.FluentMappings.Conventions.Setup(x =&gt;
                          {
                              x.AddFromAssemblyOf&lt;Program&gt;();
                              x.Add(FluentNHibernate.Conventions.Helpers.AutoImport.Never());
                          });
  
                          m.FluentMappings.AddFromAssemblyOf&lt;Mapping.MembershipMap&gt;();
                      }).BuildSessionFactory();
          }
  </code></pre>
  
  <p>So basically, within my <code>Project.Persistence</code> layer, I call the SessionFactory like this..</p>
  
  <pre><code>var session = SessionFactoryContainer.Instance.OpenSession()
  </code></pre>
  
  <p>Am I even getting close to doing this right? I'm still confused - I feel like the <code>ISessionFactory</code> should be part of <code>Castle.Windsor</code>, but I can't seem to figure out how to do that. I'm confused also about the way I am creating the Repository in the Controller. Does this mean I have to do all of the 'mapping' each time I use the Repository? That seems like it would be very resource intensive. </p>