Design Patterns

Design Patterns

Generic Factory over Object Initializers

 

Consider the following generic factory method:     public class Builder     {         public static TType Create<TType>(Action<TType> actionOnTType) where TType : new()         {             var item = new TType();             actionOnTType(item);             return item;         }     } Which allows us to do something like this:             var aRunningCar = Builder.Create<Car>(car =>             {                 car.Engine = new Engine("v8");                 car.Start();             }); What are your thoughts on the above over the standard object initializers found in C# 3.0?  Initially the difference is that this allows us to invoke methods on the instance as the instance is passed into our...

UIPAB Survey

 

The patterns & practices team is currently holding a survey about the direction of a new project aimed to fill the gaps and extend where the UIPAB left off. I am curious if they will be integrating Windows Workflow into the project as it seems to be a good fit. At TechEd this summer there were several presentations on Windows Workflow within ASP.NET by the ASP.NET team, hopefully Microsoft isn't creating two different projects with the same goals in mind. This wouldn't happen would it - Windows Communicator, Windows Messenger, MSN Messenger ;-) Go ahead and...

Model View Presenter Redux

 

The Model View Presenter (MVP) pattern seems to be all the rage within the last year; it must be the new pink. While I agree this is a great pattern to decouple various logical layers within a system, I think we are missing an important core piece to the puzzle. In my opinion, humble of course, the Model is purely a representation of my data, and I prefer to depict that in the form of a Data Transfer Object (DTO), this is the ubiquitous PONO (Plain Old .NET Object) - (Edit: Domain Model's are welcome too) . The View...

Dirty SOAP

 

I just came from Scott Hanselman and Patrick Cauldwell's session on dynamically endpoints without ASMX. Their session was great and I had the opportunity to talk with Scott for a little bit afterwards. Scott's company uses dynamic endpoints to allow their customers to easily integrate with their financial software by providing WS-I compliant web services to support integration with disparate client software. Using a dynamic adapter, they are well suited to evolve with the eminent release of WCF. Three days into TechEd and the only things missing are power strips in the session rooms (shouldn't this...

Dependency Injection with StructureMap

 

I have posted previously about using Spring.NET as an IoC container and how we can implement some of this out of the box with the System.ComponentModel namespace. StructureMap is another dependency injection framework that in my opinon is much more approachable than Spring out of the box. Why? - Let's take a look at what it takes to start requesting services from the StructureMap container.   IRule rule = ObjectFactory.GetInstance<IRule>(); or for .NET 1.1   IRule rule = ObjectFactory.GetInstance(typeof(IRule)) as IRule; To begin with, StructureMap now supports generics (granted the 1.0.2 release of Spring does as well), however...

Extending Enterprise Library 2.0

 

Brian Button, formerly of the Patterns and Practices team just held a webcast covering how to provide custom design time extensions to the Enterprise Library console. I missed his session, however after reviewing the slide deck which he has provided, extending Enterprise Library appears much easier than when I had to do it only a year ago. Definitely worth checking out if you would like to integrate your own custom extensions within Enterprise Library.

Service Locator with System.ComponentModel

 

Javier mentioned from my previous post that it would be nice to be able to request an object directly from .NET, without a reliance on the Spring Framework. To a certain extent, this is provided in the System.ComponentModel and System.ComponentModel.Design namespaces. You can create a ServiceContainer and register services with it, then if you expose your ServiceContainer as an IServiceProvider, your client can then request services back from the container. It looks something like this: IServiceContainer sc = new ServiceContainer(); sc.AddService(typeof(IDatabase), new Database()); // Add more services IServiceProvider provider = sc as IServiceProvider; Now, within another layer, assuming we have the IServiceProvider,...

Inversion of Control with Spring.NET

 

I have previously mentioned using the Spring Framework for the AOP support the framework provides, however Spring is deeply rooted in providing dependency injection or Inversion of Control (IoC). Spring uses a configuration file to manage type relationship mappings to objects, which can be stored in its own external XML file, an embedded resource within an assembly, or directly within your web.config or app.config file. For a simple example, we will define our own XML file (spring.xml), with the following contents:   <?xml version="1.0" encoding="utf-8" ?> <objects xmlns="http://www.springframework.net"> <object name="Database" singleton="false" type="SpringDemo.Database, SpringDemo"> <constructor-arg ref="SqlConnectionObject" /> <constructor-arg ref="SqlCommandObject" /> </object> <object name="SqlConnectionObject" singleton="false" type="System.Data.SqlClient.SqlConnection, System.Data"> <constructor-arg type="System.String" value="Data...

Casting in C#

 

Garrett Smith of ThoughtWorks discusses his thoughts on the two different ways of performing casting in C#. Garrett states that he prefers the C-style mechanism of casting as it "crashes early". Here's the distinction, when a cast is performed in C# using the C-style casting syntax such as the following: SomeObject s = (SomeObject)hashTable[i]; An InvalidCastException will be thrown if the cast fails. So, with defensive programming techniques, we are encouraged to wrap our code in a try/catch block. Garrett then mentions that using the "as" operator to perform casting is problematic due to the fact that no exception...

Test Driven Development on Google Groups

 

I have recently created a Google group for test driven development. If you want to discuss test driven development, regardless of the technology, feel free to stop by and join in! http://groups.google.com/group/test-driven-development

Design by Contract with AOP Revisited

 

Last night I posted a quick example of how we could place runtime requirements on methods. This is a common need by developers. I have since updated my example to clean it up a bit and make it more useable. The cleanup should make it much more extensible. In this example, I am placing two restrictions on our parameter. In order to call our function, the parameter being passed to it must be within both the minimum and maximum range defined in our PrologAttribute. What are your thoughts?   using System; using System.Reflection; using AopAlliance.Intercept; using Spring.Aop.Framework; using Spring.Aop.Interceptor; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace DeveloperNotes { public class ConstraintInterceptor : IMethodInterceptor { public object...

Design by Contract with AOP

 

Over a year ago I discussed with Joe Duffy, a program manager on the CLR team about the concept of design by contract. Recently I had a similar disucussion with Richard Hale Shaw and Cyrus Najmabadi a developer on the C# compiler team at Microsoft while I was at the MVP Global Summit. I thought I would put together a quick example of how this could be applied, spawning off of my previous post discussing AOP. This example allows the developer to place certain restrictions on a method and for those restrictions to be applied before the method is actually...

Aspect Oriented Programming with Spring and Generics

 

I wanted to post this example to flesh out an idea I was thinking about earlier today. Suppose you wanted to check permissions of a user before they made a method call, you might suggest an implementation of code access security. While that's a fair suggestion, I'd like to throw another option into the mix. With aspect oriented programming using the Spring framework, you can effectively check permissions before a method is called through the use of a proxy object that dispatches your calls to interceptors, that subsuquently invoke the requested call. Thus, depending on the results of your permission...

Assembly Probing

 

As some of you are aware, I have been working on a UITypeEditor for a custom designer in Enterprise Library. This designer will support Inversion of Control (IoC) Containers for Enterprise Library. Part of the UITypeEditor allows selecting of an assembly and class, be it installed in the GAC or a private assembly. I was running into an issue when I would load a private assembly and attempt to get it collection of types. I was using the static Assembly.LoadFrom method which worked well, except when I called GetTypes(), a ReflectionTypeLoadException exception was thrown. ReflectionTypeLoadException contains a property called LoaderExceptions,...

Composite UI Application Block

 

The group behind the Composite UI Application Block (CAB) just released a community technical preview. CAB is based on .NET 2.0 and its purpose is to allow abstract complex UI design for smart clients. If you would rather spend time working on the business specific components of your application rather than getting caught up with threading and asynchronous requests you should check this out.

PatternShare

 

PatternShare is a nice collection of enterprise patterns from various authors within the software community. You are able to view the data from many different perspectives, for example, this provides an interesting layout of all their patterns.