Corey Coogan

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

  • Subscribe

  • Archives

  • Blog Stats

    • 110,056 hits
  • Meta

Posts Tagged ‘Architecture and Design’

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.

Advertisements

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

NServiceBus and Event Driven Architecture (EDA)

Posted by coreycoogan on November 6, 2009


At the October 2009 ALT.NET Northeast Wisconsin user group, Scott Felder put together a great demonstration of NServiceBus and how it actually works. He has since followed up with a well written article on his new blog that talks about Domain Driven Design and when/where NServiceBus, or some other message bus/EDA, might fit in. It’s definitely worth a read.

Posted in Alt.Net, Architecture and Design, SOA | Tagged: , , , , | 1 Comment »

Asp.Net MVC, S#arp Architecture and Blood

Posted by coreycoogan on September 5, 2009


The Bleeding Edge

The Bleeding Edge

As mentioned in a previous post, I’ve embarked on a side project that provides tangible value to a relatively large mass of people.  This project, http://www.roomparentsonline.com, started some time ago and seemed like the perfect opportunity to move from toying with ASP.NET MVC and NHibernate to actually writing a production app with those tools.  Had I stuck with the same old stack I’m sure the project would be done by now, but instead I’m just getting started with developing actual features.  This is a very similar situation described in Rob Conery’s latest post, but I’m listening to Bad Corey and forging ahead because I really want to up my skills in this area.

So where was all my time spent?  Some was dedicated towards getting the design I got from Mark Sternig into the MVC framework.  Other time was spent getting the membership stuff setup and figuring out how I was going to lay all that out, but the other 90% was spent with Fluent NHibernate (FNH) and getting slashed by the bleeding edge of every cool OSS project out there.  Now I know why a common Alt.Net slogan is “Running with Scissors”.

S#arp Archecture 1.0 RTM

My first major hurdle was caused by the fact that I didn’t want to wait anymore for SharpArch to be released in 1.0, so I moved ahead with the latest.  I already had some significant development done when 1.0 was released 10 days later.  The RTM release was significant and fixed many issues, but there’s no way to simply upgrade the templates.  So I started by copying over all the 1.0 binaries, which caused some compatibility issues because dependencies were built against previous versions of Castle, NHibernate, etc.  I began upgrading bit by bit and found the updated classes in the new template and began to upgrade my project.  It was painful, but in the end it worked and all was good.  Time to move on to getting some mappings done.

Fluent NHibernate

For those of you not familiar with what Fluent NHibernate is, it basically lets you configure NHibernate through a fluent interface without requiring XML files.  I personally hate configuring with XML files, which is why I was so intrigued by this project.  The example project and articles I’ve read make FNH seem so simple.  It was only after I began to dive deep that I realized it seemed simple because the examples were simple.  When I tried doing things like mapping table-per-hierarchy relationships, I started pulling my hair out.  Things just didn’t work as I expected them to.  So I began to post to the FNH Group and got some great help, mostly from the creator himself, James Gregory.  Much of the advice was the same – get latest from the trunk as odds were this was a bug that’s already been fixed.

This is where the fun began.  Upgrading to FNH from the trunk meant upgrading NHibernate, meant upgrading multiple Castle projects, meant upgrading NHiberate Validator meant upgrading xVal meant upgrading all core Sharp Architecture libraries.  As you can imagine, this was going to be painful, but I saw no other option.  To make matters worse, the version from the trunk had many breaking changes so I was also breaking stuff that I actually had working.  Thankfully, Tom Cabanski informed the SharpArch group that he had rebuilt all the binaries against these latest versions and provided them in a tidy little zip file.  This was a huge help and I can’t thank Tom enough.

The Future

I’m now at a place where I can begin to actually implement features.  I’ve said a sad goodbye to my self-imposed deadline of having this app, at least registration, done by start of the 2009 school year, but I’ve learned a lot and have much more to learn.  During the upgrade process, I was also able to move to the 1.0 release of Linq to NHibernate.  It’s wonderful to think how many great projects came to fruition this summer after reading about them in their idea phase for so long.  The .NET OSS community is strong and I’m grateful to be enjoying the fruits of their labor.  Anyway, I finally figured out how to blend automappings and Fluent mappings, which was required to do class-per-hierarchy, but I’ll save that for another post.  I also have a nice validation implementation utilizing NHibernate Validator, JQuery Validation and xVal, but that post is coming as well.

Posted in ASP.NET MVC, Fluent Nhibernate, NHibernate, S#arp Architecture | Tagged: , , , , , , | 5 Comments »

ASP.NET MVC and S#arp Architecture

Posted by coreycoogan on August 21, 2009


It’s been a while since I’ve posted.  I’ve been very busy with my paying job and my side project, Room Parents Online (RPO).  For RPO, I’m using the S#arp Architecture, developed by Billy Mcafferty.  It’s a great framework for getting a new MVC project started, but one of the real benefits of using it for me was the initial setup and configuration of Fluent NHibernate.  I have never written a real production app in NH at all, so this was something I’ve been wanting to do for a long time.  There’s been plenty of pain on the bleeding edge, but more on that in future posts.

Now that I’ve laid the ground work, expect to see more posts coming from the RPO project.  I’ve been working on this project for about a month, so I have a good bit of material already, and will find the time to blog about the project regularly.  Topics to come will include:

– Automatic Model validation with xVal (this post was started 10 days ago)
– Fluent NHibernate
– NHibernate
– The pains of running with scissors
– ASP.NET MVC
– Google integration
– JQuery
– S#arp Architecture

So stay tuned for some good Alt.net stuff.

Posted in Alt.Net, Architecture and Design, ASP.NET MVC, S#arp Architecture | Tagged: , , , , , | 1 Comment »

Open/Closed Principle and Over Engineering

Posted by coreycoogan on June 18, 2009


There was a post on the Alt.net group today about how a Factory could violate OCP (Open/Closed Principle) if new methods were added. I’ve had discussions on this issue in the past and figured it deserved a post.

The Open/Closed principle is a software design principle that says:

software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification

I first learned of this principle from one of Robert C. Martin’s books, as it makes up the O in the SOLID principles. I respect SOLID and found that if you do nothing but adhere to these principles, you’ll generally design better software. It’s necessary, however, to use good judgment when applying these guidelines.

In general, OCP is the only SOLID principle that I take issue with, specifically the literal interpretation of “closed for modification”.  It seems that many developers take this to the extreme and spend unnecessary effort to avoid having to ever modify a class or method after it has been written.  The poster in the Alt.net thread was worried that adding an IF block to a method would violate OCP and was asking advice for how to avoid it.

My interpretation of OCP is that the interfaces or API’s should be closed for modification so that any future changes won’t break client or other calling code.  That means keeping your method signatures the same and not changing properties and access modifiers.  Software projects are typically time and resource sensitive and many design decisions must be weighed against the ROI they achieve.  Introducing a more complex design so that a few lines of code don’t have to be added later seems ridiculous to me.

Here’s an example where OCP doesn’t provide the necessary value to make it worth the effort.

Let’s say you have an Order entity and that entity has a Validator class.  The Validator class validates that the Order has all the required values in the right format.  This is how most of us handle validation, using some IValidator<TEntity> type of pattern.  Now let’s say that this Order class goes to production and functions properly for several months.  Now the business comes back and says that Credit Card Security Code is required for PCP compliance.  If we follow OCP in a literal sense, we can’t just add that validation rule to the Validator class.

If a person is designing with OCP in mind, they may use the Specification pattern to handle validation, which would allow us to add validation rules any time without modifying any existing classes.  That is certainly a viable option, but is not as simple and easy to understand as a single Validator class and would certainly be less effort to implement.  I would also argue that the quality of my software with a Validator class is no less than an application using Specifications for validation rules.  If my Validator is using the Notification Pattern to return validation status and error messages to various layers, adding this additional validation rule will require no modification by the rest of the application, which is what OCP means to me.

Conclusion

The SOLID principles and OCP are guidelines to help us deliver more extensible and maintainable software.  However, being a rigid and literal follower of OCP and the “closed for modification” philosophy can lead to over engineering.  Adding complexity for the sake of never touching a class or method again after it’s been written may have its place in some software projects, but chances are in most cases your quality won’t suffer by adding an IF block.

Posted in Architecture and Design, Design Patterns, SOLID | Tagged: , , | Comments Off on Open/Closed Principle and Over Engineering

Big Design Up Front (BDUF) = Booooo!

Posted by coreycoogan on June 5, 2009


I’m working on a project that is the epitome of BDUF.  After more than a 4 week effort into an end-all be-all requirements document, the technical design phase has started.  This requires the complete application design to be laid out with textual documents, Sequence Diagrams, Excel spreadsheets, class diagrams and countless other artifacts.

This is so ridiculous, as we all know that the second development begins most of those docs are out of date.  I don’t mind doing UML docs, a little at a time, but doing all of them at once really sucks.  I asked if there would be use cases, which I find to be the most useful artifact of all, but it seems they are meshed somewhere in the 70 page design document.

For those companies not quite willing to jump into a pure Agile methodology, may I suggest a hybrid between Agile and Waterfall.

– Define enough requirements to get the project going, i.e. most important features

– Design for those features

– Approve design

– Develop

– Begin requirements on next phase during development

– Review development

– Make changes as necessary

– Start over

This is sort of like a bunch of smaller water falls, but at least there is some time to react to changes from the previous iteration, which could take any amount of time.  It also breaks up the mind numbing Visio UML tasks so more attention can be focused to them.  Whose to say that one week into the project, a better flow or object model won’t be discovered, invalidating all the sequence and class diagrams developed?

UPDATE (6/8/2009): Jeff Palermo wrote on this topic with some insights into how Headspring does Agile.

Posted in Architecture and Design | Tagged: , , | 1 Comment »