Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 3500064
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 18, 20262026-05-18T12:41:18+00:00 2026-05-18T12:41:18+00:00

Prepare for a wall of code… It’s a long read, but it’s as verbose

  • 0

Prepare for a wall of code… It’s a long read, but it’s as verbose as I can get.

In response to Still lost on Repositories and Decoupling, ASP.NET MVC

I think 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.

Project

Project.Web (ASP.NET MVC 3.0 RC)

  • Uses Project.Models
  • Uses Project.Persistence

Project

Project.Models (Domain Objects)

  • Membership.Member
  • Membership.IMembershipProvider

Project

Project.Persistence (Fluent nHibernate)

  • Uses Project.Models
  • Uses Castle.Core
  • Uses Castle.Windsor

  • Membership.MembershipProvider : IMembershipProvider

I have the following class in Project.Persistence

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<T>()
        {
            return _container.Resolve<T>();
        }
    }
}
namespace Persistence.Containers.Installers
{
    public class RepositoryInstaller : IWindsorInstaller
    {
        public void Install(IWindsorContainer container, IConfigurationStore store)
        {
            container.Register(
                Component
                .For<Membership.IMembershipProvider>()
                .ImplementedBy<Membership.MembershipProvider>()
                .LifeStyle.Singleton
            );
        }
    }
}

Now, in Project.Web Global.asax Application_Start, I have the following code.

    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);

        // Register the Windsor Container
        Project.Persistence.IoC.Initialize();
    }

Now then, in Project.Web.Controllers.MembershipController I have the following code.

    [HttpPost]
    public ActionResult Register( Web.Models.Authentication.Registration model)
    {
        if (ModelState.IsValid)
        {
            var provider = IoC.Resolve<Membership.IMembershipProvider>();
            provider.CreateUser(model.Email, model.Password);
        }

        // If we got this far, something failed, redisplay form
        return View(model);
    }

So I am asking first of all..

Am I on the right track?

How can I use Castle.Windsor for my ISessionFactory

I have my SessionFactory working like this …

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 => c.Is(connectionString)))
                    .ExposeConfiguration(config =>
                    {
                        new NHibernate.Tool.hbm2ddl.SchemaExport(config)
                            .SetOutputFile("Output.sql")
                            .Create(/* Output to console */ false, /* Execute script against database */ createSchema);
                    })
                    .Mappings(m =>
                    {
                        m.FluentMappings.Conventions.Setup(x =>
                        {
                            x.AddFromAssemblyOf<Program>();
                            x.Add(FluentNHibernate.Conventions.Helpers.AutoImport.Never());
                        });

                        m.FluentMappings.AddFromAssemblyOf<Mapping.MembershipMap>();
                    }).BuildSessionFactory();
        }

So basically, within my Project.Persistence layer, I call the SessionFactory like this..

var session = SessionFactoryContainer.Instance.OpenSession()

Am I even getting close to doing this right? I’m still confused – I feel like the ISessionFactory should be part of Castle.Windsor, 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.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-18T12:41:18+00:00Added an answer on May 18, 2026 at 12:41 pm

    Firstly some conceptual details. In an ASP.NET MVC application the typical entry point for a page request is a controller. We want the Inversion of Control container to resolve our controllers for us, because then any dependencies that the controllers have can also be automatically resolved simply by listing the dependencies as arguments in the controllers’ constructors.

    Confused yet? Here’s an example of how you’d use IoC, after it is all set up. I think explaining it this way makes things easier!

    public class HomeController : Controller
    {
        // lets say your home page controller depends upon two providers
        private readonly IMembershipProvider membershipProvider;
        private readonly IBlogProvider blogProvider;
    
        // constructor, with the dependencies being passed in as arguments
        public HomeController(
                    IMembershipProvider membershipProvider,
                    IBlogProvider blogProvider)
        {
            this.membershipProvider = membershipProvider;
            this.blogProvider = blogProvider;
        }
    
        // so taking your Registration example...
        [HttpPost]
        public ActionResult Register( Web.Models.Authentication.Registration model)
        {
            if (ModelState.IsValid)
            {
                this.membershipProvider.CreateUser(model.Email, model.Password);
            }
    
            // If we got this far, something failed, redisplay form
            return View(model);
        }
    }
    

    Note that you have not had to do any resolving yourself, you have just specified in the controller what the dependencies are. Nor have you actually given any indication of how the dependencies are implemented – it’s all decoupled. It’s very simple there is nothing complicated here 🙂

    Hopefully at this point you are asking, “but how does the constructor get instantiated?” This is where we start to set up your Castle container, and we do this entirely in the MVC Web project (not Persistence or Domain). Edit the Global.asax file, setting Castle Windsor to act as the controller factory:

    protected void Application_Start()
    {
    //...   
        ControllerBuilder.Current
            .SetControllerFactory(typeof(WindsorControllerFactory));
    }
    

    …and define the WindsorControllerFactory so that your controllers are instantiated by Windsor:

    /// Use Castle Windsor to create controllers and provide DI
    public class WindsorControllerFactory : DefaultControllerFactory
    {
        private readonly IWindsorContainer container;
    
        public WindsorControllerFactory()
        {
            container = ContainerFactory.Current();
        }
    
        protected override IController GetControllerInstance(
            RequestContext requestContext,
            Type controllerType)
        {
            return (IController)container.Resolve(controllerType);
        }
    }
    

    The ContainerFactory.Current() method is static singleton that returns a configured Castle Windsor container. The configuration of the container instructs Windsor on how to resolve your application’s dependencies. So for example, you might have a container configured to resolve the NHibernate SessionFactory, and your IMembershipProvider.

    I like to configure my Castle container using several “installers”. Each installer is responsible for a different type of dependency, so I’d have a Controller installer, an NHibernate installer, a Provider installer for example.

    Firstly we have the ContainerFactory:

    public class ContainerFactory
    {
        private static IWindsorContainer container;
        private static readonly object SyncObject = new object();
    
        public static IWindsorContainer Current()
        {
            if (container == null)
            {
                lock (SyncObject)
                {
                    if (container == null)
                    {
                        container = new WindsorContainer();
                        container.Install(new ControllerInstaller());
                        container.Install(new NHibernateInstaller());
                        container.Install(new ProviderInstaller());
                    }
                }
            }
            return container;
        }
    }
    

    …and then we need each of the installers. The ControllerInstaller first:

    public class ControllerInstaller : IWindsorInstaller
    {
        public void Install(IWindsorContainer container, IConfigurationStore store)
        {
            container.Register(
                AllTypes
                    .FromAssembly(Assembly.GetExecutingAssembly())
                    .BasedOn<IController>()
                    .Configure(c => c.Named(
                        c.Implementation.Name.ToLowerInvariant()).LifeStyle.PerWebRequest));
        }
    }
    

    … and here is my NHibernateInstaller although it is different to yours, you can use your own configuration. Note that I’m reusing the same ISessionFactory instance every time one is resolved:

    public class NHibernateInstaller : IWindsorInstaller
    {
        private static ISessionFactory factory;
        private static readonly object SyncObject = new object();
    
        public void Install(IWindsorContainer container, IConfigurationStore store)
        {
            var windsorContainer = container.Register(
                Component.For<ISessionFactory>()
                    .UsingFactoryMethod(SessionFactoryFactory));
        }
    
        private static ISessionFactory SessionFactoryFactory()
        {
            if (factory == null)
            {
                lock (SyncObject)
                {
                    if (factory == null)
                    {
                        var cfg = new Configuration();
                        factory = cfg.Configure().BuildSessionFactory();
                    }
                }
            }
    
            return factory;
        }
    }
    

    And finally you’ll want to define your ProvidersInstaller:

    public class ProvidersInstaller : IWindsorInstaller
    {
        public void Install(IWindsorContainer container, IConfigurationStore store)
        {
            var windsorContainer = container
                .Register(
                    Component
                        .For<IMembershipProvider>()
                        .ImplementedBy<SubjectQueries>())
                .Register(
                    Component
                        .For<IBlogProvider>()
                        .ImplementedBy<SubjectQueries>());
    
                // ... and any more that your need to register
        }
    }
    

    This should be enough code to get going! Hopefully you’re still with me as the beauty of the Castle container becomes apparent very shortly.

    When you define your implementation of your IMembershipProvider in your persistence layer, remember that it has a dependency on the NHibernate ISessionFactory. All you need to do is this:

    public class NHMembershipProvider : IMembershipProvider
    {
        private readonly ISessionFactory sessionFactory;
    
        public NHMembershipProvider(ISessionFactory sessionFactory)
        {
            this.sessionFactory = sessionFactory;
        }
    }
    

    Note that because Castle Windsor is creating your controllers and the providers passed to your controller constructor, the provider is automatically being passed the ISessionFactory implementation configured in your Windsor container!

    You never have to worry about instantiating any dependencies again. Your container does it all automatically for you.

    Finally, note that the IMembershipProvider should be defined as part of your domain, as it is defining the interface for how your domain behaviours. As noted above, the implementation of your domain interfaces which deal with databases are added to the persistence layer.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Should I prepare my code for possible/predicted future changes so that it's easier to
We were using stringstream to prepare select queries in C++. But we were strongly
I have this partial code: if ($getRecords = $con->prepare(SELECT * FROM AUCTIONS WHERE ARTICLE_NO
How do you prepare your SQL deltas? do you manually save each schema-changing SQL
I need to prepare for my exam and this is the probable question for
I'm trying to use SQLBindParameter to prepare my driver for input via SQLPutData .
I have a SqlCommand that I want to call Prepare() on whose CommandType =
Ok so i want to do a prepared insert such as: prepare(INSERT INTO `analyzeditemsdetails`
Does anybody knows which charset is used in Moldava. We to prepare our software
If I've been churning away at the code for a while, and forgotten to

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.