Corey Coogan

Python, .Net, C#, ASP.NET MVC, Architecture and Design

  • Subscribe

  • Archives

  • Blog Stats

    • 109,869 hits
  • Meta

Posts Tagged ‘Design Patterns’

Castle Windsor Tutorial in Asp.Net MVC

Posted by coreycoogan on November 6, 2009


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.


//my repository class from the Data assembly
namespace S2sol.Rpo.Data
{
     public class ClassroomRepository : S2sol.Rpo.Core.DataInterfaces.IClassroomRepository
    {
    }
}

//my Repository interface from the Core assembly
namespace S2sol.Rpo.Core.DataInterfaces
{
    public interface IClassroomRepository
    {
    }
}

//this is how I would resolve an IClassroomRepository to its implementation from Castle
IClassroomRepository 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.

private static void AddRepositoriesTo(IWindsorContainer container)
{
    container.Register(
    AllTypes.Pick()
    .FromAssembly(typeof(UserRepository).Assembly) //get the assembly where this repository lives
    .WithService.FirstNonGenericCoreInterface("S2sol.Rpo.Core") //look for interfaces from this assembly
    );
}

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.

private static void AddApplicationServicesTo(IWindsorContainer container)
{
      container.Register(
        AllTypes.Pick()
        .FromAssembly(typeof(ProfileService).Assembly)
        .WithService.FirstInterface());
}

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.

private static void AddControllersTo(IWindsorContainer container)
{
	container.RegisterControllers(typeof(HomeController).Assembly);
}

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.

container.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.

//constructor for the UserSession implementation
public UserSession(IProfileService profileSerivce,
            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.

container.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.

private static void AddSecurityConcernsTo(IWindsorContainer container)
{
	container.Register(Component.For<IIdentity>()
	  .LifeStyle.PerWebRequest
	  .UsingFactoryMethod(() => HttpContext.Current.User.Identity));

	container.Register(Component.For<IPrincipal>()
	  .LifeStyle.PerWebRequest
	  .UsingFactoryMethod(() => HttpContext.Current.User));
	
	container.Register(Component.For<HttpSessionStateBase>()
		.LifeStyle.PerWebRequest
		.UsingFactoryMethod(() => new HttpSessionStateWrapper(HttpContext.Current.Session)));


}

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.

ControllerBuilder.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.

ServiceLocator.SetLocatorProvider(() => new WindsorServiceLocator(container));

Bringing it all Together

Now I’ll just put everything together for your copy/paste pleasure.

Global.asax

protected void Application_Start()
{
	InitializeServiceLocator();

	//do everything else here
}

/// <summary>
/// Instantiate the container and add all Controllers that derive from 
/// WindsorController to the container.  Also associate the Controller 
/// with the WindsorContainer ControllerFactory.
/// </summary>
protected virtual void InitializeServiceLocator()
{
	//create the container
	IWindsorContainer container = new WindsorContainer();
	//set the controller factory
	ControllerBuilder.Current.SetControllerFactory(new WindsorControllerFactory(container));
	//configure the container
	ComponentRegistrar.AddComponentsTo(container);
	//setup the common service locator
	ServiceLocator.SetLocatorProvider(() => new WindsorServiceLocator(container));
}

ComponentRegistrar.cs

public class ComponentRegistrar
    {
        public static void AddComponentsTo(IWindsorContainer container)
        {
            container.AddFacility<FactorySupportFacility>();

            AddControllersTo(container);
            AddGenericRepositoriesTo(container);
            AddCustomRepositoriesTo(container);
            AddApplicationServicesTo(container);
            AddOneOffs(container);
            AddSecurityConcernsTo(container);
        }

		//add all my controllers
        private static void AddControllersTo(IWindsorContainer container)
        {
            container.RegisterControllers(typeof(HomeController).Assembly);
        }

		//handle any one off registrations that aren't convention based
        private static void AddOneOffs(IWindsorContainer container)
        {
            container.AddComponent<SharpArch.Core.CommonValidator.IValidator,Validator>("validator");
        }

       //handle registrations for my security classes
        private static void AddSecurityConcernsTo(IWindsorContainer container)
        {
            container.Register(Component.For<IIdentity>()
              .LifeStyle.PerWebRequest
              .UsingFactoryMethod(() => HttpContext.Current.User.Identity));

            container.Register(Component.For<IPrincipal>()
              .LifeStyle.PerWebRequest
              .UsingFactoryMethod(() => HttpContext.Current.User));
            
            container.Register(Component.For<HttpSessionStateBase>()
                .LifeStyle.PerWebRequest
                .UsingFactoryMethod(() => new HttpSessionStateWrapper(HttpContext.Current.Session)));


        }


		//register my application services
        private static void AddApplicationServicesTo(IWindsorContainer container)
        {
            container.Register(
                AllTypes.Pick()
                .FromAssembly(typeof(ProfileService).Assembly)
                .WithService.FirstInterface());
        }
		
		//register all custom repositories (not generic)
        private static void AddCustomRepositoriesTo(IWindsorContainer container)
        {
            container.Register(
                AllTypes.Pick()
                .FromAssembly(typeof(UserRepository).Assembly)
                .WithService.FirstNonGenericCoreInterface("S2sol.Rpo.Core"));
        }

		//register all my SharpArch generic repos
        private static void AddGenericRepositoriesTo(IWindsorContainer container)
        {
            container.AddComponent("entityDuplicateChecker",
                typeof(IEntityDuplicateChecker), typeof(EntityDuplicateChecker));
            container.AddComponent("repositoryType",
                typeof(IRepository<>), typeof(Repository<>));
            container.AddComponent("nhibernateRepositoryType",
                typeof(INHibernateRepository<>), typeof(NHibernateRepository<>));
            container.AddComponent("repositoryWithTypedId",
                typeof(IRepositoryWithTypedId<,>), typeof(RepositoryWithTypedId<,>));
            container.AddComponent("nhibernateRepositoryWithTypedId",
                typeof(INHibernateRepositoryWithTypedId<,>), typeof(NHibernateRepositoryWithTypedId<,>));

        }
    }

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.

Posted in Alt.Net, Architecture and Design, ASP.NET, ASP.NET MVC, Design Patterns, IoC, Uncategorized | Tagged: , , , , , , , , , , , , , | 23 Comments »

Visitor Pattern: A Real World Example

Posted by coreycoogan on June 16, 2009


Vistor

Vistor

The Visitor pattern is a powerful design pattern that I see a lot less then its popular brethren such as Factory, Facade, Command and Singleton. I believe this is because the pattern is often a bit more difficult for developers to understand and much of the articles and examples out there lack a real world example.

The Gang of Four defines the Visitor as:

Represent an operation to be performed on elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates.

The very nature of the Visitor makes it an ideal pattern to plug into public API’s, thus allowing its clients to perform operations on a class using a “visiting” class without having to modify the source. Once familiar with this pattern, you will see the opportunity to apply it whenever you are dealing with composites or collections of interfaces/base classes.

A Real World Example

I have been working on a project that uses a third-party application database. The database is very large and provides a set of base tables that are completely generic. These tables look much like what you find in SharePoint, with column names like CHAR_01, CHAR_02, DATE_01, DATE_02. The application adds meaning to these generic tables by creating Views with meaningful column names in the database to sit on top of them. For example, the EntryView will essentially map a field called BeginDate to the base table’s DATE_01 field.

A code generator has been written to interact with this database from .Net applications. The generator creates of class for each base table as well as a class for each view, which decorates the base table.

Here’s what that table/view structure looks coming out of the generator:

    public class BaseTableRecord
    {
        public int Int01 { get; set; }
        public string Char01 { get; set; }
        public bool Char02 { get; set; }
        public bool Bool01 { get; set; }
    }

    public abstract class PartyBaseView
    {
        public PartyBaseView (BaseTableRecord record)
        {
            BaseRecord = record;
        }

        public BaseTableRecord BaseRecord { get; private set; }
    }

    public class PartyEntryView : PartyBaseView
    {
        public PartyEntryView (BaseTableRecord record)
            : base(record)
        { }

        public int NumberInParty
        {
            get { return BaseRecord.Int01; }
            set { BaseRecord.Int01 = value; }
        }

        public string PartyName
        {
            get { return BaseRecord.Char01; }
            set { BaseRecord.Char01 = value; }
        }
    }

    public class PartyExitView : PartyBaseView
    {
        public PartyExitView (BaseTableRecord record)
            : base(record)
        { }

        public int ExitingParty
        {
            get { return BaseRecord.Int01; }
            set { BaseRecord.Int01 = value; }
        }

        public string Payor
        {
            get { return BaseRecord.Char01; }
            set { BaseRecord.Char01 = value; }
        }
    }

To remain generic, the primary type that is deal with is a collection of PartyViewBase types. Now there are all sorts of actions we will want to perform on these different views. Because any single Use Case could deal with a collection of PartyViewBase types, consisting of one or more instances of multiples PartyViewBase implementations, we need a way to interact with each inside an iteration without casting. A perfect example Use Case would be the need to map each view to an XML file. Let’s see how Visitor pattern (which will ultimately have to be added to the code generator) will work for me.

First I’m going to define the IPartyViewVisitor interface for my Visitor:

    public interface IPartyViewVisitor
    {
        void Visit(PartyEntryView view);
        void Visit(PartyExitView view);
    }

Now I’m going to add a method to my PartyBaseView to allow the methods on my visitor to be invoked. Here’s what that abstract method looks like:

public abstract void Accept(IPartyViewVisitor vistor);

Here’s what the classes look like now that they’ve fully implemented the pattern:

    public abstract class PartyViewBase
    {
        public PartyViewBase(BaseTableRecord record)
        {
            BaseRecord = record;
        }

        public BaseTableRecord BaseRecord { get; private set; }

        public abstract void Accept(IPartyViewVisitor vistor);
    }

    public class PartyEntryView : PartyViewBase
    {
        public PartyEntryView(BaseTableRecord record)
            : base(record)
        { }

        public override void Accept(IPartyViewVisitor vistor)
        {
            vistor.Visit(this);
        }

        public int NumberInParty
        {
            get { return BaseRecord.Int01; }
            set { BaseRecord.Int01 = value; }
        }

        public string PartyName
        {
            get { return BaseRecord.Char01; }
            set { BaseRecord.Char01 = value; }
        }

    }

    public class PartyExitView : PartyViewBase
    {
        public PartyExitView(BaseTableRecord record)
            : base(record)
        { }

        public override void Accept(IPartyViewVisitor vistor)
        {
            vistor.Visit(this);
        }

        public int ExitingParty
        {
            get { return BaseRecord.Int01; }
            set { BaseRecord.Int01 = value; }
        }

        public string Payor
        {
            get { return BaseRecord.Char01; }
            set { BaseRecord.Char01 = value; }
        }
    }

Next, I need to write an IPartyViewVisitor implementation to handle mapping my Views to XML files.

    public class PartyViewMapperVisitor : IPartyViewVisitor
    {
        //would take some infrastructure class in the constructor

        #region IPartyViewVisitor Members

        public void Visit(PartyEntryView view)
        {
            //do mapping here
            Console.WriteLine("Mapping PartyEntryView");
        }

        public void Visit(PartyExitView view)
        {
            //do maping here
            Console.WriteLine("Mapping PartyExitView");
        }

        #endregion
    }

Now I’ll put it all together and get a list of PartyViewBase instances, loop through them, and let my Visitor implementation do the work.

    //instantiate my repository, service or whatever
    PartyRepository repo = new PartyRepository();

    //get my list of PartyViewBase instances
    IList parties = repo.GetAllParties();

    //instantiate my mapping visitor
    PartyViewMapperVisitor visitor = new PartyViewMapperVisitor();

    //loop through my PartyViewBase instances
    foreach (var viewBase in parties)
    {
         //perform my mapping
         viewBase.Accept(visitor);
    }

Conclusion

The Visitor pattern allows you to define an operation on a class without changing that class. Because a Visitor is defined as an interface, visitor implementations can be written for multiple needs and the target class never gets touched, adhering to OCP. Whenever you are dealing with composites, think about using the Visitor pattern to make your life easier. It’s also great to stub the Visitor into public API’s to grant your clients, and yourself, future access without modification.

Posted in Architecture and Design, Design Patterns | Tagged: , , | 5 Comments »