<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom"
	xml:lang="en">
	<title>.NET Junkie</title>
	<subtitle>Weblog of a workaholic</subtitle>
        <link rel="alternate" type="text/html" href="http://www.cuttingedge.it/blogs/steven/index.php"/>
        <link rel="self" type="application/atom+xml" href="http://www.cuttingedge.it/blogs/steven/atom.xml"/>
	<updated>2012-04-24T11:25:48+02:00</updated>
	<author>
	<name></name>
	<uri>http://www.cuttingedge.it/blogs/steven/index.php</uri>
	<email>steven at this domain</email>
	</author>
	<id>tag:pivotpowered,2012:NETJunkie</id>
	<generator uri="http://www.pivotlog.net" version="Pivot - 1.40.7: 'Dreadwind'">Pivot</generator>
	<rights>Copyright (c) 2012, Authors of .NET Junkie</rights>
	
	
	
	<entry>
		<title>Returning data from command handlers</title>
		<link rel="alternate" type="text/html" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=93" />
		<updated>2012-04-24T11:25:00+02:00</updated>
		<published>2012-04-14T15:36:00+02:00</published>
		<id>tag:pivotpowered,2012:NETJunkie.93</id>
		<link rel="related" type="text/html" href=""  />
		<summary type="text">This article extends the architectural design of command handlers to allow command handlers to return data.</summary>
        <content type="html" xml:lang="en" xml:base="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=93"><![CDATA[
                This article extends the architectural design of command handlers to allow command handlers to return data.<p>A few months back I described <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=91" title=".NET Junkie - Meanwhile&hellip; on the command side of my architecture">the command / handler architecture</a> that I (and many others) use to effectively model business operations in a system. Once in a while a question pops up in my mail or at <a rel="external" href="http://www.stackoverflow.com" title="Stackoverflow">Stackoverflow</a> about returning data from a command.</p><p>It seems strange at first to return data from commands, since the whole idea of the <a rel="external" href="http://en.wikipedia.org/wiki/Command-query_separation" title="Wikipedia - Command-query separation">Command-query separation</a> is that a function should either return a value or mutate state, but not both. So without any more context, I would respond to such question with: separate the returning of the data from the operation that mutates the state. Execute that command and <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=92" title=".NET Junkie - Meanwhile&hellip; on the query side of my architecture">execute a query</a> after the command has finished.</p><p>When we take a closer look at the question however, we will usually see that the data being returned is an Identifier of some sort, which is the result of the creation of some entity in the system. Take a look at the following command:</p><pre class="cs" language="csharp" customtypes="CreateCustomerCommand Address ActionResult CreateCustomerCommandHandler ICommandHandler IUnitOfWorkFactory NorthwindUnitOfWork Customer IPostCommitRegistrator UnitOfWork PostCommitRegistratorImpl PostCommitCommandHandlerDecorator TransactionCommandHandlerDecorator" customvaluetypes="PutYourCustomValueTypesHere">public class CreateCustomerCommand<br />{<br />    public string Name { get; set; }<br />    public Address Address { get; set; }<br />    public DateTime? DateOfBirth { get; set; }<br />}<br /></pre><p>Since the command will create a new customer, it&rsquo;s not unlikely for the caller to need the id of the customer, for instance to redirect to another page:</p><pre class="cs" language="csharp" customtypes="CreateCustomerCommand Address ActionResult CreateCustomerCommandHandler ICommandHandler IUnitOfWorkFactory NorthwindUnitOfWork Customer IPostCommitRegistrator UnitOfWork PostCommitRegistratorImpl PostCommitCommandHandlerDecorator TransactionCommandHandlerDecorator" customvaluetypes="PutYourCustomValueTypesHere">public ActionResult CreateCustomer(<br />    CreateCustomerCommand command)<br />{<br />    this.handler.Handle(command);<br />    int customerId = [get the customer Id here];<br />    return this.RedirectToAction(&quot;Index&quot;, <br />        new { id = customerId });<br />}</pre><p>Still, do we really want to return values from commands? A few things to note here. First of all, returning values from commands does mean that a command can never be executed asynchronously anymore, something that architectures such as <a rel="external" href="http://martinfowler.com/bliki/CQRS.html" title="Martin Fowler - CQRS">CQRS</a> promote. Besides this, the <span class="type">CreateCustomerCommand</span> seems very CRUDy, and probably doesn&rsquo;t really fit an architecture like CQRS. In a CQRS like architecture, you are likely to report to your user the message &ldquo;your request is being processed&rdquo; or might want to poll until the operation has executed asynchronously.</p><p>For the systems I&rsquo;m working on, for my customers, my fellow developers, and even myself, CQRS is a bridge too far. The idea of having all commands (possibly) execute asynchronously &ndash;and CQRS itself- is a real mind shift that I&rsquo;m currently not willing to make (yet), and I can&rsquo;t expect other developers to do to. With my current state of mind, it is simply too useful to have commands handlers return data to the caller. So how do we do that?</p><p>The answer is actually very simple: Define an &lsquo;output&rsquo; property on a command:</p><pre class="cs" language="csharp" customtypes="CreateCustomerCommand Address ActionResult CreateCustomerCommandHandler ICommandHandler IUnitOfWorkFactory NorthwindUnitOfWork Customer IPostCommitRegistrator UnitOfWork PostCommitRegistratorImpl PostCommitCommandHandlerDecorator TransactionCommandHandlerDecorator" customvaluetypes="PutYourCustomValueTypesHere">public class CreateCustomerCommand<br />{<br />    public string Name { get; set; }<br />    public Address Address { get; set; }<br />    public DateTime? DateOfBirth { get; set; }<br /><br />    // output property<br />    public int CustomerId { get; internal set; }<br />}</pre><p>When a command handler sets this property during the execution, the caller can use it as follows:</p><pre class="cs" language="csharp" customtypes="CreateCustomerCommand Address ActionResult CreateCustomerCommandHandler ICommandHandler IUnitOfWorkFactory NorthwindUnitOfWork Customer IPostCommitRegistrator UnitOfWork PostCommitRegistratorImpl PostCommitCommandHandlerDecorator TransactionCommandHandlerDecorator" customvaluetypes="PutYourCustomValueTypesHere">public ActionResult CreateCustomer(<br />    CreateCustomerCommand command)<br />{<br />    this.handler.Handle(command);<br />    int customerId = command.CustomerId;<br />    return this.RedirectToAction(&quot;Index&quot;, <br />        new { id = customerId });<br />}</pre><p>We can set this id from within the command handler:</p><pre class="cs" language="csharp" customtypes="CreateCustomerCommand Address ActionResult CreateCustomerCommandHandler ICommandHandler IUnitOfWorkFactory NorthwindUnitOfWork Customer IPostCommitRegistrator UnitOfWork PostCommitRegistratorImpl PostCommitCommandHandlerDecorator TransactionCommandHandlerDecorator" customvaluetypes="PutYourCustomValueTypesHere">public class CreateCustomerCommandHandler <br />    : ICommandHandler&lt;CreateCustomerCommand&gt;<br />{<br />    IUnitOfWorkFactory&lt;NorthwindUnitOfWork&gt; factory;<br /><br />    public CreateCustomerCommandHandler(<br />        IUnitOfWorkFactory&lt;NorthwindUnitOfWork&gt; factory)<br />    {<br />        this.factory = factory;<br />    }<br /> <br />    public void Handle(CreateCustomerCommand command)<br />    {<br />        using (var unitOfWork = this.factory.CreateNew())<br />        {<br />            var customer = new Customer<br />            {<br />                Name = command.Name,<br />                Street = command.Address.Street,<br />                City = command.Address.City,<br />                DateOfBirth = command.DateOfBirth,<br />            };<br /> <br />            unitOfWork.Customers.InsertOnSubmit(customer);<br /><br />            unitOfWork.Commit();<br /><br />            // Set the output property.<br />            command.CustomerId = customer.Id;<br />        } <br />    }<br />}</pre><p>As you can see, the <span class="code">CustomerId</span> property of the <span class="type">CreateCustomerCommand</span> is set at the end of the <span class="code">Handle</span> method of the handler. This sounds too good to be true, and well&hellip; it depends ;-).</p><p>When the <span class="type">Customer</span><span class="code">.Id</span> is generated by the database, the <span class="code">Commit</span> will ensure that the <span class="type">Customer</span> is persisted and will retrieve the auto-generated key and it will become available immediately after the <span class="code">Commit</span>. We can therefore simply set the command&rsquo;s <span class="code">CustomerId</span> property after calling <span class="code">Commit</span>.</p><p>The previous command handler was in complete control over the unit of work. It created that unit of work, it committed that unit of work, and it disposed that unit of work. This is a simple model I effectively used in the past, and I know others are still using this today. Letting the command handler control the unit of work however, has its short comes.</p><p>This design works great when commands are small and contain little logic. It starts to fall apart however, when commands get more complex and start to depend on other abstractions that need to run in the same context / unit of work. When the unit of work is controlled by the command handler, it is the handler's responsibility of passing it on to its dependencies, and since those dependencies are already created at the time the handler creates the unit of work, constructor injection is out of the picture. The only thing left is passing the unit of work through method arguments (method injection). Although it doesn&rsquo;t seem that bad, I worked on a system where we actually did this, but the call stacks were deep and passing around the unit of work from method to method, from class to class was just tedious. To make our lives easier we started creating a new unit of work for some operations, but this actually made things worse, since a single use case / request resulted in multiple unit of works, which sometimes lead to very strange behavior, or even deadlocks.</p><p>For this reason, I stepped away from this design and instead I inject a unit of work instance into classes that need it. Though, somebody somewhere in the system must manage the unit of work. This can be solved by registering the unit of work with a Per Thread or Per Web Request lifetime and implementing a command handler decorator that will ensure the unit of work is committed after the handler completed successfully (note that committing the unit of work on the end of the web request is typically a bad idea, since there is no way to tell whether the unit of work should actually be committed at that point). You have to realize that, although simplifying your application code, the complexity is moved into the <a rel="external" href="http://blog.ploeh.dk/2011/07/28/CompositionRoot.aspx" title="Mark Seemann's blog - Composition Root">composition root</a>. The size and complexity of your application must promote this. Although I must admit that once familiar with these types of constructions and configurations of your composition root, you will find it easy to apply in small systems as well.</p><p>One note about database generated keys. CQRS models the business around aggregate roots (a <a rel="external" href="http://en.wikipedia.org/wiki/Domain-driven_design" title="Wikipedia - Domain-driven design">DDD</a> concept), and each aggregate root gets a unique key, usually generated as a Guid, which can be generated in .NET. This means that when using CQRS, you will never run into the problem of database generated keys, which is great of course.</p><p>Aggregates in DDD are a group of domain objects that belong together. The Aggregate Root is the thing that holds them together. An <span class="type">Order</span> for instance, may have order lines and those order lines cannot live without that order. The order is therefore the aggregate root and has an unique identifier. An order line does not need an identifier, since it will never be referenced directly; other aggregates will only reference the order, never the lines. They may need an identitier in your relational database, but you would probably never return them from a command, since they are purely internal to the Aggregate. If such identitier is needed, returned, or referenced from other aggregates, they are probably not part of that aggregate and the system is incorrectly modeled, accordingly to DDD. This also means that the system will have not as many primary keys as a non-DDD system will have. In a normal relational database, each order line will usually get its own auto number primary key. In that case, it will be much more likely to get into performance problems when using Guids. A Guid is 16 bytes (12 bytes bigger than an Int32) and every database index of a certain table will contain the primary key of that table, making each index 12 bytes times the number of records in the table bigger. Disk space is cheap, but I/O isn&rsquo;t. When doing complex queries over large amounts of data, lowering the amount of I/O is important. And don&rsquo;t forget the clustered index fragmentation that random Guids cause.</p><p>Long story short, you might be in the situation where you don&rsquo;t use DDD / CQRS, want to return a database generated value from your command handlers, while having a design were command handler don&rsquo;t control the unit of work. How do we do this?</p><p>Since database generated IDs only come available after the data is saved to the database, and committing happens after the handler executed, we need a construct that allows the handlers to execute some code after the commit operation. We can introduce a new abstraction to the system, where command handlers can depend upon, which allows them to register some post-commit operation:</p><pre class="cs" language="csharp" customtypes="CreateCustomerCommand Address ActionResult CreateCustomerCommandHandler ICommandHandler IUnitOfWorkFactory NorthwindUnitOfWork Customer IPostCommitRegistrator UnitOfWork PostCommitRegistratorImpl PostCommitCommandHandlerDecorator TransactionCommandHandlerDecorator" customvaluetypes="PutYourCustomValueTypesHere">public interface IPostCommitRegistrator<br />{<br />    event Action Committed;<br />}</pre><p>This interface defines a single event, which command handlers can depend upon and register their post commit operation. The previously defined <span class="type">CreateCustomerCommandHandler</span> will now look like this:</p><pre class="cs" language="csharp" customtypes="CreateCustomerCommand Address ActionResult CreateCustomerCommandHandler ICommandHandler IUnitOfWorkFactory NorthwindUnitOfWork Customer IPostCommitRegistrator UnitOfWork PostCommitRegistratorImpl PostCommitCommandHandlerDecorator TransactionCommandHandlerDecorator" customvaluetypes="PutYourCustomValueTypesHere">public class CreateCustomerCommandHandler <br />    : ICommandHandler&lt;CreateCustomerCommand&gt;<br />{<br />    private readonly UnitOfWork unitOfWork;<br />    private readonly IPostCommitRegistrator postCommit;<br /><br />    public CreateCustomerCommandHandler(<br />        UnitOfWork unitOfWork,<br />        IPostCommitRegistrator postCommit)<br />    {<br />        this.unitOfWork = unitOfWork;<br />        this.postCommit= postCommit;<br />    }<br /> <br />    public void Handle(CreateCustomerCommand command)<br />    {<br />        var customer = new Customer<br />        {<br />            Name = command.Name,<br />            Street = command.Address.Street,<br />            City = command.Address.City,<br />            DateOfBirth = command.DateOfBirth,<br />        };<br /> <br />        this.unitOfWork.Customers.InsertOnSubmit(customer);<br /> <br />        // Register an event that will be called after commit.<br />        this.postCommit.Committed += () =&gt;<br />        {<br />            // Set the output property.<br />            command.CustomerId = customer.Id;<br />        };<br />    }<br />}</pre><p>This command handler registers a delegate to the <span class="type">IPostCommitRegistrator</span>, which is injected through the constructor (note that you should only inject the <span class="type">IPostCommitRegistrator </span>into a handler that actually needs it).</p><p>From the application design, this really is all there&rsquo;s to it. However, there is some more work to do inside the composition root. For instance, we need an implementation of this <span class="type">IPostCommitRegistrator</span>:</p><pre class="cs" language="csharp" customtypes="CreateCustomerCommand Address ActionResult CreateCustomerCommandHandler ICommandHandler IUnitOfWorkFactory NorthwindUnitOfWork Customer IPostCommitRegistrator UnitOfWork PostCommitRegistratorImpl PostCommitCommandHandlerDecorator TransactionCommandHandlerDecorator" customvaluetypes="PutYourCustomValueTypesHere">private sealed class PostCommitRegistratorImpl <br />    : IPostCommitRegistrator<br />{<br />    public event Action Committed = () =&gt; { };<br /> <br />    public void OnCommitted()<br />    {<br />        this.Committed();<br /> <br />        // Clear the list after calling.<br />        this.Committed = () =&gt; { };<br />    }<br />}</pre><p>This implementation is very simple. It just implements the <span class="code">Committed</span> event and defines an <span class="code">OnCommitted</span> method, which will be called from the code that manages the transactional behavior of the command handlers. In my <a rel="external" href="entry.php?id=91" title=".NET Junkie - Meanwhile&hellip; on the command side of my architecture">previous post</a> I defined an <span class="type">TransactionCommandHandlerDecorator</span><span class="code">&lt;T&gt;</span>, which allowed executing the commands in a transactional manner. Although we can extend this class to add this post commit behavior, I like my classes to be focused, and have a single responsibility. Let&rsquo;s define a <span class="type">PostCommitCommandHandlerDecorator</span><span class="code">&lt;T&gt;</span>, that has the sole responsibility of executing the registered post commit delegates, after a transaction was committed successfully:</p><pre class="cs" language="csharp" customtypes="CreateCustomerCommand Address ActionResult CreateCustomerCommandHandler ICommandHandler IUnitOfWorkFactory NorthwindUnitOfWork Customer IPostCommitRegistrator UnitOfWork PostCommitRegistratorImpl PostCommitCommandHandlerDecorator TransactionCommandHandlerDecorator" customvaluetypes="PutYourCustomValueTypesHere">private sealed class PostCommitCommandHandlerDecorator&lt;T&gt;<br />    : ICommandHandler&lt;T&gt;<br />{<br />    private readonly ICommandHandler&lt;T&gt; decorated;<br />    private readonly PostCommitRegistratorImpl registrator;<br /> <br />    public PostCommitCommandHandlerDecorator(<br />        ICommandHandler&lt;T&gt; decorated,<br />        PostCommitRegistratorImpl registrator)<br />    {<br />        this.decorated = decorated;<br />        this.registrator = registrator;<br />    }<br /> <br />    public void Handle(T command)<br />    {<br />        this.decorated.Handle(command);<br /> <br />        this.registrator.OnCommitted();<br />    }<br />}</pre><p>This decorator depends on the <span class="type">PostCommitRegistratorImpl</span> directly and during the Handle method -after the transaction completes successfully- the <span class="code">OnCommitted</span> method of the <span class="type">PostCommitRegistratorImpl</span> is called. Note that this decorator depends on the <span class="type">PostCommitRegistratorImpl</span>  implementation and not on the <span class="type">IPostCommitRegistrator</span> interface. The interface does not implement the <span class="code">OnCommitted</span> method, and we don&rsquo;t want it to, since we don&rsquo;t want any command handler to call that method directly. We do however want this class to be able to execute the registered delegates, so we need it to access the implementation. Since both classes are part of the composition root, this is fine. The application code itself has no notion of the <span class="type">PostCommitRegistratorImpl</span> nor the <span class="type">PostCommitCommandHandlerDecorator</span><span class="code">&lt;T&gt;</span>.</p><p>Our last task is to wire up all the dependencies correctly. This isn&rsquo;t really difficult, but does need a certain state of mind, since you need to carefully consider the lifestyle of <span class="type">PostCommitRegistratorImpl</span>. Up until this point this article was container agnostic. Here is an example of how to configure this using the <a rel="external" href="http://simpleinjector.codeplex.com" title="Simple Injector">Simple Injector</a>:</p><pre class="cs" language="csharp" customtypes="CreateCustomerCommand Address ActionResult CreateCustomerCommandHandler ICommandHandler IUnitOfWorkFactory NorthwindUnitOfWork Customer IPostCommitRegistrator UnitOfWork PostCommitRegistratorImpl PostCommitCommandHandlerDecorator TransactionCommandHandlerDecorator" customvaluetypes="PutYourCustomValueTypesHere">using SimpleInjector;<br />using SimpleInjector.Extensions;<br /><br />container.RegisterManyForOpenGeneric(<br />    typeof(ICommandHandler&lt;&gt;), <br />    typeof(ICommandHandler&lt;&gt;).Assembly);<br /><br />container.RegisterOpenGenericDecorator(<br />    typeof(ICommandHandler&lt;&gt;), <br />    typeof(TransactionCommandHandlerDecorator&lt;&gt;));<br /><br />container.RegisterOpenGenericDecorator(<br />    typeof(ICommandHandler&lt;&gt;), <br />    typeof(PostCommitCommandHandlerDecorator&lt;&gt;));<br /> <br />container.RegisterPerWebRequest&lt;PostCommitRegistratorImpl&gt;();<br />container.Register&lt;IPostCommitRegistrator&gt;(<br />    () =&gt; container.GetInstance&lt;PostCommitRegistratorImpl&gt;());</pre><p>The previous registration does a few things:</p><ul><li>First it registers all public <span class="type">ICommandHandler</span><span class="code">&lt;T&gt;</span> implementations  that live in the same assembly as the <span class="type">ICommandHandler</span><span class="code">&lt;T&gt;</span> does.</li><li>Next it registers the <span class="type">TransactionCommandHandlerDecorator</span><span class="code">&lt;T&gt;</span> to be wrapped around each command handler implementation. </li><li>Next it registers the <span class="type">PostCommitCommandHandlerDecorator</span><span class="code">&lt;T&gt;</span> to be  wrapped around each <span class="type">TransactionCommandHandlerDecorator</span><span class="code">&lt;T&gt;</span>  implementation. It is important that the post commit decorator is  wrapped around the transaction decorator, since the system will behave  incorrectly when they are decorated the other way around, since that  means that the registered delegates would be called before the  transaction is committed.</li><li>The <span class="type">PostCommitRegistratorImpl</span> is registered. Since we want to inject the  same instance in both the command handler and the post commit  decorator, we can&rsquo;t use the <a rel="external" href="http://simpleinjector.codeplex.com/wikipage?title=ObjectLifestyleManagement#Transient" title="Simple Injector - Transient lifestyle">transient lifestyle</a>, since that will  new up a new instance each time it is injected. Using a single instance  for the whole application however, is only possible when the application  is single-threaded (which can be the case if you run the handlers in a  Windows Forms application or a Windows Service). In this case I assume a  web application, which is inherently multi-threaded. I therefore  register it on a Per Request basis (the <a rel="external" href="http://simpleinjector.codeplex.com/wikipage?title=ObjectLifestyleManagement#PerWebRequest" title="Simple Injector - Per Web Request">RegisterPerWebRequest</a> is an  extension method that can be found in the Simple Injector  documentation).</li><li>Since the application does not depend on <span class="type">PostCommitRegistratorImpl</span> but  on the <span class="type">IPostCommitRegistrator</span> interface, we need to map that interface  to the previous registration. This is done by registering a delegate  that requests the <span class="type">PostCommitRegistratorImpl</span>. This may look odd, but is  an effective way to <a rel="external" href="http://simpleinjector.codeplex.com/wikipage?title=How-to#Register_Multiple_Interfaces_With_The_Same_Implementation" title="Simple Injector - Documentation - How To - Register Multiple Interfaces With The Same Implementation">map multiple interfaces to the same implementation</a>. The delegate is called every time an <span class="type">IPostCommitRegistrator</span> is  injected, but since it requests a <span class="type">PostCommitRegistratorImpl</span>, which is  registered on a Per Web Request basis, it will always return the same  instance for a single request.</li></ul><h5>Conclusion</h5><p>Again, one simple abstraction can solve the problem we have effectively. Nice about this design is that it keeps the code of the commands handlers pretty clean, and although not shown, it is easy to write unit tests for this as well.</p>
		]]></content>
		<author>
			<name>Steven</name>
		</author>
	</entry>
	
	
	
	<entry>
		<title>Meanwhile… on the query side of my architecture</title>
		<link rel="alternate" type="text/html" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=92" />
		<updated>2012-02-19T14:52:00+02:00</updated>
		<published>2011-12-18T17:19:00+02:00</published>
		<id>tag:pivotpowered,2012:NETJunkie.92</id>
		<link rel="related" type="text/html" href=""  />
		<summary type="text">Command-query separation is a common concept in the software industry. It is fairly common to model the command side as a message passing system with handlers that process such a message. This same concept is equally usable at the query side, but is very uncommon. This article tries to change this. Three simple interfaces will change the look of your architecture% forever.</summary>
        <content type="html" xml:lang="en" xml:base="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=92"><![CDATA[
                Command-query separation is a common concept in the software industry. It is fairly common to model the command side as a message passing system with &lsquo;handlers&rsquo; that process such a message. This same concept is equally usable at the query side, but is very uncommon. This article tries to change this. Three simple interfaces will change the look of your architecture&hellip; forever.<p>In <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=91" title=".NET Junkie - Meanwhile&hellip; on the command side of my architecture">my previous post</a> I described how I design the command side of my architecture. The greatest part of this design is that it enables a lot of flexibility, and lowers the overall complexity of the system, just by adding a simple interface to the system and grouping business logic in a certain manner. The design is founded on the <a rel="external" href="http://en.wikipedia.org/wiki/SOLID" title="Wikipedia - SOLID">SOLID</a> principles and brought to life with <a rel="external" href="http://en.wikipedia.org/wiki/Dependency_injection" title="Wikipedia - Dependency Injection">DI</a>. Please read that post, if you haven&rsquo;t yet. It will refer to its content often.</p><p>It&rsquo;s funny though, that I encountered the command/handler design a few years ago, but never understood why you would use two classes (a command and a handler) for one single operation. It just didn&rsquo;t seem very object oriented to me. It was only after I experienced problems with the old design, that the usefulness of the command/handler design became clear to me.</p><p>It was this type of discomfort that triggered me to think about the design of a different part of my application architecture. Although the part of the business layer that handles business processes was modeled uniformly and allowed great flexibility, that same didn&rsquo;t hold for the part of the business layer that was responsible to querying. For the query side I modeled queries as methods with clear names and grouped them together in a class. This lead to interfaces like the following:</p><pre class="cs" language="csharp" customtypes="AppDomain Consumer Container Controller ValidationQueryHandlerDecorator DebuggerStepThrough FakeFailingUserQueries FakeUserServicesUserQueries FindUsersBySearchTextQuery FindUsersBySearchTextQueryHandler GetCurrentTimeQuery GetCurrentUserIdQuery GetHighUsageUsersQuery GetRecentOrdersForLoggedInUserQuery GetUsersByRolesQuery IQuery IQueryExecuter IQueryHandler IQueryProcessor IServiceProvider IUserQueries NorthwindUnitOfWork QueryExecuter QueryProcessor Required StringLength User UserController UserInfo UserQueryHandlers ValidationContext Validator" customvaluetypes="PutYourCustomValueTypesHere">public interface IUserQueries<br />{<br />    User[] FindUsersBySearchText(string searchText, <br />        bool includeInactiveUsers);<br /> <br />    User[] GetUsersByRoles(string[] roles);<br /> <br />    UserInfo[] GetHighUsageUsers(int reqsPerDayThreshold);<br /><br />    // More methods here<br />}</pre><p>Besides this <span class="type">IUserQueries</span> interface, there were interfaces such as <span class="type">IPatientInfoQueries</span>, <span class="type">ISurgeryQueries</span>, and many, many more, each had its own set of methods with own set of parameters  and return types. Every interface was different, which made adding cross-cutting concerns, such as logging and audit trailing, which I often wanted to add to all queries, very hard. Besides that, I was missing the same uniformity in the design, that I had with my command handlers. Those query classes were just a bunch of random methods, often grouped around one concept or one entity, or at least I tried. Still, it looked messy and every time a query method was added, the interface and the implementation of that interface had to be changed.</p><p>In my automated test suite it even got worse. A class under test that depended on such a query interface was often only expected to call one or two of the methods of such interface, while other classes were expected to call other methods on it. This lead me to assert that a class didn&rsquo;t call unexpected methods, which resulted in the creation of an abstract base class in my test project that implemented that interface, that looked like this:</p><pre class="cs" language="csharp" customtypes="AppDomain Assert Consumer Container Controller ValidationQueryHandlerDecorator DebuggerStepThrough FakeFailingUserQueries FakeUserServicesUserQueries FindUsersBySearchTextQuery FindUsersBySearchTextQueryHandler GetCurrentTimeQuery GetCurrentUserIdQuery GetHighUsageUsersQuery GetRecentOrdersForLoggedInUserQuery GetUsersByRolesQuery IQuery IQueryExecuter IQueryHandler IQueryProcessor IServiceProvider IUserQueries NorthwindUnitOfWork QueryExecuter QueryProcessor Required StringLength User UserController UserInfo UserQueryHandlers ValidationContext Validator" customvaluetypes="PutYourCustomValueTypesHere">public abstract class FakeFailingUserQueries : IUserQueries<br />{<br />    public virtual User[] FindUsersBySearchText(<br />        string searchText, bool includeInactive)<br />    {<br />        Assert.Fail(&quot;Call to this method was not expected.&quot;);<br />        return null;<br />    }<br /> <br />    public virtual User[] GetUsersByRoles(string[] roles)<br />    {<br />        Assert.Fail(&quot;Call to this method was not expected.&quot;);<br />        return null;<br />    }<br />        <br />    public virtual UserInfo[] GetHighUsageUsers(<br />        int requestsPerDayThreshold)<br />    {<br />        Assert.Fail(&quot;Call to this method was not expected.&quot;);<br />        return null;<br />    }<br /><br />    // More methods here<br />}</pre><p>For a certain set of tests I would then override this base class and implement one of the methods:</p><pre class="cs" language="csharp" customtypes="AppDomain Consumer Container Controller ValidationQueryHandlerDecorator DebuggerStepThrough FakeFailingUserQueries FakeUserServicesUserQueries FindUsersBySearchTextQuery FindUsersBySearchTextQueryHandler GetCurrentTimeQuery GetCurrentUserIdQuery GetHighUsageUsersQuery GetRecentOrdersForLoggedInUserQuery GetUsersByRolesQuery IQuery IQueryExecuter IQueryHandler IQueryProcessor IServiceProvider IUserQueries NorthwindUnitOfWork QueryExecuter QueryProcessor Required StringLength User UserController UserInfo UserQueryHandlers ValidationContext Validator" customvaluetypes="PutYourCustomValueTypesHere">public class FakeUserServicesUserQueries : FakeFailingUserQueries<br />{<br />    public User[] UsersToReturn { get; set; }<br /> <br />    public string[] CalledRoles { get; private set; }<br /> <br />    public override User[] GetUsersByRoles(string[] roles)<br />    {<br />        this.CalledRoles = roles;<br /> <br />        return this.UsersToReturn;<br />    }<br />}</pre><p>This way I could let all other methods fail, since they were not expected to be called, while preventing me from having to write too much code. However, this still lead to an explosion of test classes in my test projects.</p><p>Of course al the described problems can be solved with &lsquo;proper&rsquo; tooling. For instance, cross-cutting concerns can be added by using <a rel="external" href="http://en.wikipedia.org/wiki/Aspect-oriented_programming" title="Wikipedia - Aspect oriented programming">Aspect Oriented Programming</a> using attributes and code weaving, or by configuring your DI container using convention based registration, mixed with interception, which uses dynamic proxy generation and lightweight code generation. The testing problems could be fixed by using Mocking frameworks, which also generate proxy classes that act like the original class.</p><p>Although all these solutions work, they only makes things more complicated, and they are patches to hide problems with the initial design. When we validate the design against the five <a rel="external" href="http://en.wikipedia.org/wiki/SOLID" title="Wikipedia - SOLID">SOLID</a> principles, we can see clearly where the problem lies. The design violates two out of five SOLID rules.</p><p>The design violates the <a rel="external" href="http://en.wikipedia.org/wiki/Open/closed_principle" title="Wikipedia - Open/closed principle">Open/Closed Principle</a>, because almost every time a query is added to the system, an existing interface -and its implementations- need to be changed. Every interface has at least two implementations (one real implementation and one test implementation).</p><p>The <a rel="external" href="http://en.wikipedia.org/wiki/Interface_segregation_principle" title="Wikipedia - Interface segregation principle">Interface Segregation Principle</a> is violated, because the interfaces are wide (have many methods) and consumers of those interfaces are forced to depend on methods that they don&rsquo;t use.</p><p>So let us not treat the symptoms; let&rsquo;s fix the cause.</p><h4>A better design<a name="Better-Design" title="Better-Design"></a></h4><p>Instead of having a separate interface per group of queries, we can define a single interface for all queries in the system, just as we saw with the <span class="type">ICommandHandler</span><span class="code">&lt;TCommand&gt;</span> interface in my previous article. We need to define the following two interfaces:</p><pre class="cs" language="csharp" customtypes="AppDomain Consumer Container Controller ValidationQueryHandlerDecorator DebuggerStepThrough FakeFailingUserQueries FakeUserServicesUserQueries FindUsersBySearchTextQuery FindUsersBySearchTextQueryHandler GetCurrentTimeQuery GetCurrentUserIdQuery GetHighUsageUsersQuery GetRecentOrdersForLoggedInUserQuery GetUsersByRolesQuery IQuery IQueryExecuter IQueryHandler IQueryProcessor IServiceProvider IUserQueries NorthwindUnitOfWork QueryExecuter QueryProcessor Required StringLength User UserController UserInfo UserQueryHandlers ValidationContext Validator" customvaluetypes="PutYourCustomValueTypesHere">public interface IQuery&lt;TResult&gt;<br />{<br />}<br /> <br />public interface IQueryHandler&lt;TQuery, TResult&gt;<br />    where TQuery : IQuery&lt;TResult&gt;<br />{<br />    TResult Handle(TQuery query);<br />}</pre><p>The <span class="type">IQuery</span><span class="code">&lt;TResult&gt;</span> specifies an object that can be used to query data, and it defines the data it returns using the TResult generic type. In a sense it&rsquo;s the counterpart of a command. This interface doesn&rsquo;t have any members (it is not a marker interface, since it contains a generic type argument) and doesn&rsquo;t look very useful, but bear with me, as I will explain this later on why having such interface is very useful.</p><p>Although commands are (most often) fire and forget that (usually) don&rsquo;t return a value, queries are the opposite in that we don&rsquo;t expect a query to change state, and do expect a return value. Now we can define a query object like this:</p><pre class="cs" language="csharp" customtypes="AppDomain Consumer Container Controller ValidationQueryHandlerDecorator DebuggerStepThrough FakeFailingUserQueries FakeUserServicesUserQueries FindUsersBySearchTextQuery FindUsersBySearchTextQueryHandler GetCurrentTimeQuery GetCurrentUserIdQuery GetHighUsageUsersQuery GetRecentOrdersForLoggedInUserQuery GetUsersByRolesQuery IQuery IQueryExecuter IQueryHandler IQueryProcessor IServiceProvider IUserQueries NorthwindUnitOfWork QueryExecuter QueryProcessor Required StringLength User UserController UserInfo UserQueryHandlers ValidationContext Validator" customvaluetypes="PutYourCustomValueTypesHere">public class FindUsersBySearchTextQuery : IQuery&lt;User[]&gt;<br />{<br />    public string SearchText { get; set; }<br /> <br />    public bool IncludeInactiveUsers { get; set; }<br />}</pre><p>This class defines a query operation with two parameters, which will result in an array of <span class="type">User</span> objects. Note btw that this query class is a <a rel="external" href="http://martinfowler.com/refactoring/catalog/introduceParameterObject.html" title="Martin Fowler - Refactoring - Introduce Parameter Object">Parameter Object</a>. The class that executes this query can be defined as follows:</p><pre class="cs" language="csharp" customtypes="AppDomain Consumer Container Controller ValidationQueryHandlerDecorator DebuggerStepThrough FakeFailingUserQueries FakeUserServicesUserQueries FindUsersBySearchTextQuery FindUsersBySearchTextQueryHandler GetCurrentTimeQuery GetCurrentUserIdQuery GetHighUsageUsersQuery GetRecentOrdersForLoggedInUserQuery GetUsersByRolesQuery IQuery IQueryExecuter IQueryHandler IQueryProcessor IServiceProvider IUserQueries NorthwindUnitOfWork QueryExecuter QueryProcessor Required StringLength User UserController UserInfo UserQueryHandlers ValidationContext Validator" customvaluetypes="PutYourCustomValueTypesHere">public class FindUsersBySearchTextQueryHandler<br />    : IQueryHandler&lt;FindUsersBySearchTextQuery, User[]&gt;<br />{<br />    private readonly NorthwindUnitOfWork db;<br /> <br />    public FindUsersBySearchTextQueryHandler(<br />        NorthwindUnitOfWork db)<br />    {<br />        this.db = db;<br />    }<br /> <br />    public User[] Handle(FindUsersBySearchTextQuery query)<br />    {<br />        return (<br />            from user in this.db.Users<br />            where user.Name.Contains(query.SearchText)<br />            select user)<br />            .ToArray();<br />    }<br />}</pre><p>Just as we&rsquo;ve seen with the command handlers, we can now let consumers depend the generic <span class="type">IQueryHandler</span> interface:</p><pre class="cs" language="csharp" customtypes="AppDomain Consumer Container Controller ValidationQueryHandlerDecorator DebuggerStepThrough FakeFailingUserQueries FakeUserServicesUserQueries FindUsersBySearchTextQuery FindUsersBySearchTextQueryHandler GetCurrentTimeQuery GetCurrentUserIdQuery GetHighUsageUsersQuery GetRecentOrdersForLoggedInUserQuery GetUsersByRolesQuery IQuery IQueryExecuter IQueryHandler IQueryProcessor IServiceProvider IUserQueries NorthwindUnitOfWork QueryExecuter QueryProcessor Required StringLength User UserController UserInfo UserQueryHandlers ValidationContext Validator" customvaluetypes="PutYourCustomValueTypesHere">public class UserController : Controller<br />{<br />    IQueryHandler&lt;FindUsersBySearchTextQuery, User[]&gt; handler;<br /> <br />    public UserController(<br />        IQueryHandler&lt;FindUsersBySearchTextQuery, User[]&gt; handler)<br />    {<br />        this. handler = handler;<br />    }<br /> <br />    public View SearchUsers(string searchString)<br />    {<br />        var query = new FindUsersBySearchTextQuery<br />        {<br />            SearchText = searchString,<br />            IncludeInactiveUsers = false<br />        };<br /> <br />        User[] users = this.handler.Handle(query);<br /><br />        return this.View(users);<br />    }<br />}</pre><p>Immediately this model gives us a lot of flexibility, because we can now decide what to inject into the <span class="type">UserController</span>. As we&rsquo;ve seen in the previous article, we can inject a completely different implementation, or one that wraps the real implementation, without having to make changes to the <span class="type">UserController</span> (and all other consumers of that interface).</p><p>Injecting the <span class="type">IQueryHandler</span> interface into a consumer however, has a few less obvious problems that need to be addressed. The most important problem is that this solution isn&rsquo;t as type safe as it seems at first. Say for instance that we change the previously defined <span class="type">FindUsersBySearchTextQueryHandler</span> to return an <span class="type">IQueryable</span><span class="code">&lt;</span><span class="type">User</span><span class="code">&gt;</span> instead of a <span class="type">User</span><span class="code">[]</span>. Changing a return type is something I tend to do regularly during development. This can simply be achieved by letting the query object implement <span class="type">IQuery</span><span class="code">&lt;</span><span class="type">IQueryable</span><span class="code">&lt;</span><span class="type">User</span><span class="code">&gt;</span><span class="code">&gt;</span>, letting the handler implement <span class="type">IQueryHandler</span><span class="code">&lt;</span><span class="type">FindUsersBySearchTextQuery</span><span class="code">, </span><span class="type">IQueryable</span><span class="code">&lt;</span><span class="type">User</span><span class="code">&gt;&gt;</span>, and of course we need to change the handler to make it return an <span class="type">IQueryable</span> (by removing the <span class="code">ToArray</span> call). Even though we didn&rsquo;t change the <span class="type">UserController</span>, the whole application will now compile again, although the <span class="type">UserController</span> now depends on an interface for which there is no implementation. Instead, this will fail at runtime when the DI container tries to create a new <span class="type">UserController</span> for us. I rather see this fail at compile time.</p><p>Another problem is the number of dependencies our consumers will get. It is called <a rel="external" href="http://blog.ploeh.dk/2010/01/20/RebuttalConstructorOverinjectionAntipattern.aspx" title="Mark Seemann's blog - Rebuttal: Constructor over-injection anti-pattern">constructor over-injection</a> when a constructor takes many arguments (the rule of thumb is more than 5). This is an anti-pattern and is often a signal of the violation of the <a rel="external" href="http://en.wikipedia.org/wiki/Single_responsibility_principle" title="Wikipedia - Single responsibility principle">Single Responsibility Principle</a> (SRP). Although it is important to adhere to the SRP, it is very likely that consumers execute many different queries, without really violating the SRP. I experienced the number of queries a class executes to change frequently, which also triggers changes in the number of constructor arguments.</p><p>This leads us to the last shortcoming of this approach, which is that the generic structure of the <span class="type">IQueryHandler</span><span class="code">&lt;TQuery, TResult&gt;</span> leads to a lot of infrastructural code, which makes reading the code harder. Take for instance at the following class:</p><pre class="cs" language="csharp" customtypes="AppDomain Consumer Container Controller ValidationQueryHandlerDecorator DebuggerStepThrough FakeFailingUserQueries FakeUserServicesUserQueries FindUsersBySearchTextQuery FindUsersBySearchTextQueryHandler GetCurrentTimeQuery GetCurrentUserIdQuery GetHighUsageUsersQuery GetRecentOrdersForLoggedInUserQuery GetUsersByRolesQuery IQuery IQueryExecuter IQueryHandler IQueryProcessor IServiceProvider IUserQueries NorthwindUnitOfWork QueryExecuter QueryProcessor Required StringLength User UserController UserInfo UserQueryHandlers ValidationContext Validator" customvaluetypes="PutYourCustomValueTypesHere">public class Consumer<br />{<br />    IQueryHandler&lt;FindUsersBySearchTextQuery, IQueryable&lt;UserInfo&gt;&gt; findUsers;<br />    IQueryHandler&lt;GetUsersByRolesQuery, IEnumerable&lt;User&gt;&gt; getUsers;<br />    IQueryHandler&lt;GetHighUsageUsersQuery, IEnumerable&lt;UserInfo&gt;&gt; getHighUsage;<br /> <br />    public Consumer(<br />        IQueryHandler&lt;FindUsersBySearchTextQuery, IQueryable&lt;UserInfo&gt;&gt; findUsers,<br />        IQueryHandler&lt;GetUsersByRolesQuery, IEnumerable&lt;User&gt;&gt; getUsers,<br />        IQueryHandler&lt;GetHighUsageUsersQuery, IEnumerable&lt;UserInfo&gt;&gt; getHighUsage)<br />    {<br />        this.findUsers = findUsers;<br />        this.getUsers = getUsers;<br />        this.getHighUsage = getHighUsage;<br />    }<br />}</pre><p>Wow!! That&rsquo;s a lot of code. And this class only has three different queries it wishes to execute.</p><p>So how do we fix these problems? As always, with an extra layer of abstraction. We need a mediator that sits in between the consumers and the query handlers:</p><pre class="cs" language="csharp" customtypes="AppDomain Consumer Container Controller ValidationQueryHandlerDecorator DebuggerStepThrough FakeFailingUserQueries FakeUserServicesUserQueries FindUsersBySearchTextQuery FindUsersBySearchTextQueryHandler GetCurrentTimeQuery GetCurrentUserIdQuery GetHighUsageUsersQuery GetRecentOrdersForLoggedInUserQuery GetUsersByRolesQuery IQuery IQueryExecuter IQueryHandler IQueryProcessor IServiceProvider IUserQueries NorthwindUnitOfWork QueryExecuter QueryProcessor Required StringLength User UserController UserInfo UserQueryHandlers ValidationContext Validator" customvaluetypes="PutYourCustomValueTypesHere">public interface IQueryProcessor<br />{<br />    TResult Execute&lt;TResult&gt;(IQuery&lt;TResult&gt; query);<br />}</pre><p>The <span class="type">IQueryProcessor</span> is a non-generic interface with one (generic) method. Remember how our query objects implemented the <span class="type">IQuery</span><span class="code">&lt;TResult&gt;</span> interface? This is why we need it. By letting the query define its return type, we can have compile time support in our consumers. Let&rsquo;s rewrite the <span class="type">UserController</span> to use the new <span class="type">IQueryProcessor</span>:</p><pre class="cs" language="csharp" customtypes="View AppDomain Consumer Container Controller ValidationQueryHandlerDecorator DebuggerStepThrough FakeFailingUserQueries FakeUserServicesUserQueries FindUsersBySearchTextQuery FindUsersBySearchTextQueryHandler GetCurrentTimeQuery GetCurrentUserIdQuery GetHighUsageUsersQuery GetRecentOrdersForLoggedInUserQuery GetUsersByRolesQuery IQuery IQueryExecuter IQueryHandler IQueryProcessor IServiceProvider IUserQueries NorthwindUnitOfWork QueryExecuter QueryProcessor Required StringLength User UserController UserInfo UserQueryHandlers ValidationContext Validator" customvaluetypes="PutYourCustomValueTypesHere">public class UserController : Controller<br />{<br />    private IQueryProcessor queryProcessor;<br /> <br />    public UserController(IQueryProcessor queryProcessor)<br />    {<br />        this.queryProcessor = queryProcessor;<br />    }<br /> <br />    public View SearchUsers(string searchString)<br />    {<br />        var query = new FindUsersBySearchTextQuery<br />        {<br />            SearchText = searchString<br />        };<br /> <br />        // Note how we omit the generic type argument,<br />        // but still have type safety.<br />        User[] users = this.queryProcessor.Execute(query);<br /><br />        return this.View(users);<br />    }<br />}</pre><p>See how the UserController now depends on a <span class="type">IQueryProcessor</span> that can handle all kinds of queries. The <span class="type">UserController</span>&rsquo;s <span class="code">SearchUsers</span> method now calls the <span class="type">IQueryProcessor</span><span class="code">.Execute</span> method supplying the query object. Since the <span class="type">FindUsersBySearchTextQuery</span> implement the <span class="type">IQuery</span><span class="code">&lt;</span><span class="type">User</span><span class="code">[]&gt;</span> interface, we can supply it to this generic <span class="code">Execute&lt;TResult&gt;(</span><span class="type">IQuery</span><span class="code">&lt;TResult&gt; query)</span> method. Because of <a rel="external" href="http://msdn.microsoft.com/en-us/library/twcad0zb%28v=vs.80%29.aspx" title="MSDN - Generic Methods (C# Programming Guide)">C# type inference</a>, the C# compiler is able to determine the used generic type and this prevents us from spelling the generic type out. And because of this, the return type of the <span class="code">Execute</span> method is also known. Thus, when we let the <span class="type">FindUsersBySearchTextQuery</span> implement a different interface, say <span class="type">IQuery</span><span class="code">&lt;</span><span class="type">IQueryable</span><span class="code">&lt;</span><span class="type">User</span><span class="code">&gt;&gt;</span>, the <span class="type">UserController</span> will not compile anymore, instead of failing at runtime. Of course it is still possible for the system not to contain a handler for a specific query, but that is much less likely to happen, and it is much easier to write some code that will validate this (either in a unit test, or in the start-up path of the application).</p><p>Now it is the responsibility of the implementation of the <span class="type">IQueryProcessor</span> interface to find out which <span class="type">IQueryHandler</span> it should get to execute. It takes a bit of dynamic typing, and the use of a Dependency Injection container, but can be done with just a few lines of code:</p><pre class="cs" language="csharp" customtypes="AppDomain Consumer Container Controller ValidationQueryHandlerDecorator DebuggerStepThrough FakeFailingUserQueries FakeUserServicesUserQueries FindUsersBySearchTextQuery FindUsersBySearchTextQueryHandler GetCurrentTimeQuery GetCurrentUserIdQuery GetHighUsageUsersQuery GetRecentOrdersForLoggedInUserQuery GetUsersByRolesQuery IQuery IQueryExecuter IQueryHandler IQueryProcessor IServiceProvider IUserQueries NorthwindUnitOfWork QueryExecuter QueryProcessor Required StringLength User UserController UserInfo UserQueryHandlers ValidationContext Validator" customvaluetypes="PutYourCustomValueTypesHere">sealed class QueryProcessor : IQueryProcessor<br />{<br />    private readonly Container container;<br /><br />    public QueryProcessor(Container container)<br />    {<br />        this.container = container;<br />    }<br /><br />    [DebuggerStepThrough]<br />    public TResult Execute&lt;TResult&gt;(IQuery&lt;TResult&gt; query)<br />    {<br />        var handlerType = typeof(IQueryHandler&lt;,&gt;)<br />            .MakeGenericType(query.GetType(), typeof(TResult));<br /><br />        dynamic handler = container.GetInstance(handlerType);<br /><br />        return handler.Handle((dynamic)query);<br />    }<br />}<br /></pre><p>This <span class="type">QueryProcessor</span> class constructs a specific <span class="type">IQueryHandler</span><span class="code">&lt;TQuery, TResult&gt;</span> <span class="type">Type</span> based on the supplied query instance. This type is used to ask the supplied container class to get a new instance of that handler. Unfortunately we need to call the Handle method using reflection (by using the C# 4.0 <span class="keyword">dymamic</span> keyword), because at that point it is impossible to cast the handler instance, since the generic <span class="code">TQuery</span> argument is not available at compile time. However, unless the <span class="code">Handle</span> method is renamed or gets other arguments, this call will never fail, and if you wish, it is very easy to write a unit test for that. There&rsquo;s only a slight drop in performance when doing this, but nothing much to worry about (especially when you're using the <a rel="external" href="http://simpleinjector.codeplex.com/wikipage?title=ObjectLifestyleManagement#PerWebRequest" title="Simple Injector">Simple Injector</a> as your DI container, because <a rel="external" href="http://www.palmmedia.de/Blog/2011/8/30/ioc-container-benchmark-performance-comparison" title="IoC Container Benchmark - Performance comparison">it is blazingly fast).</a></p><p>I did consider an alternative design of the <span class="type">IQueryProcessor</span> interface by the way, that looked like this:</p><pre class="cs" language="csharp" customtypes="AppDomain Consumer Container Controller ValidationQueryHandlerDecorator DebuggerStepThrough FakeFailingUserQueries FakeUserServicesUserQueries FindUsersBySearchTextQuery FindUsersBySearchTextQueryHandler GetCurrentTimeQuery GetCurrentUserIdQuery GetHighUsageUsersQuery GetRecentOrdersForLoggedInUserQuery GetUsersByRolesQuery IQuery IQueryExecuter IQueryHandler IQueryProcessor IServiceProvider IUserQueries NorthwindUnitOfWork QueryExecuter QueryProcessor Required StringLength User UserController UserInfo UserQueryHandlers ValidationContext Validator" customvaluetypes="PutYourCustomValueTypesHere">public interface IQueryProcessor<br />{<br />    TResult Execute&lt;TQuery, TResult&gt;(TQuery query)<br />        where TQuery : IQuery&lt;TResult&gt;;<br />}</pre><p>This interface does solve the problem of having to do dynamic typing in the <span class="type">QueryProcessor</span> implementation completely, but unfortunately the C# compiler isn&rsquo;t &lsquo;smart&rsquo; enough to find out which types are needed (<a rel="external" href="http://blogs.msdn.com/b/ericlippert/archive/2009/12/10/constraints-are-not-part-of-the-signature.aspx" title="Eric Lippert's blog - Constraints are not part of the signature">damn you Anders</a>!), which forces us to completely write out the call to Execute, including both the generic arguments, which gets really ugly. I was a bit amazed by this, because I was under the assumption that the C# compiler could get this.</p><p>There&rsquo;s one important thing you should be aware of when using the <span class="type">IQueryProcessor</span> abstraction. By injecting an <span class="type">IQueryProcessor</span>, we make it unclear which queries a consumer is using. This makes unit testing more fragile, since the constructor doesn&rsquo;t state what the class depends on. I believe we can live with this, but wouldn&rsquo;t use this sort of abstraction too often. I wouldn&rsquo;t want to have an <span class="type">ICommandProcessor</span> for executing commands, for instance. The reason for this is that no extra compile time support is needed for commands, and consumers are less likely to take a dependency on many command handlers. And if they do, they are probably violating the SRP.</p><p>A consequence of this design however, is that there will be a lot of small classes in the system. I personally like having a lot of small / focused classes (with clear names), but in this scenario, it might give some overhead, since every query handler would have a constructor that takes some dependencies and stores them in local variables.</p><p>There are ways to remove that overhead, if it bothers you. You can for instance merge multiple query handlers into a single class, as follows:</p><pre class="cs" language="csharp" customtypes="AppDomain Consumer Container Controller ValidationQueryHandlerDecorator DebuggerStepThrough FakeFailingUserQueries FakeUserServicesUserQueries FindUsersBySearchTextQuery FindUsersBySearchTextQueryHandler GetCurrentTimeQuery GetCurrentUserIdQuery GetHighUsageUsersQuery GetRecentOrdersForLoggedInUserQuery GetUsersByRolesQuery IQuery IQueryExecuter IQueryHandler IQueryProcessor IServiceProvider IUserQueries NorthwindUnitOfWork QueryExecuter QueryProcessor Required StringLength User UserController UserInfo UserQueryHandlers ValidationContext Validator" customvaluetypes="PutYourCustomValueTypesHere">public class UserQueryHandlers :<br />    IQueryHandler&lt;FindUsersBySearchTextQuery, User[]&gt;,<br />    IQueryHandler&lt;GetUsersByRolesQuery, User[]&gt;,<br />    IQueryHandler&lt;GetHighUsageUsersQuery, UserInfo[]&gt;<br />{<br />    private readonly NorthwindUnitOfWork db;<br /> <br />    public UserQueryHandlers(NorthwindUnitOfWork db)<br />    {<br />        this.db = db;<br />    }<br /> <br />    public User[] Handle(FindUsersBySearchTextQuery query)<br />    {<br />        return (<br />            from user in this.db.Users<br />            where user.Name.Contains(query.SearchText)<br />            select user)<br />            .ToArray();<br />    }<br /> <br />    public User[] Handle(GetUsersByRolesQuery query)<br />    {<br />        // Query here<br />    }<br /> <br />    public UserInfo[] Handle(GetHighUsageUsersQuery query)<br />    {<br />        // Query here<br />    }<br /><br />    // More methods here.<br />}</pre><p>Although this <span class="type">UserQueryHandlers</span> class really looks like the initial design we tried to prevent, there is one crucial difference:  it implements <span class="type">IQueryHandler</span><span class="code">&lt;TQuery, TResult&gt;</span> multiple times, once per query. This allows us to register this class multiple times, once per implemented interface. This gives us all the previously described advantages.</p><p>When using a Dependency Injection framework (which is probably advisable with this model), we can often register all query handlers with a single call (depending on your framework of choice), simply because all handlers implement the <span class="type">IQueryHandler</span><span class="code">&lt;TQuery, TResult&gt;</span> interface. Your mileage may vary, but with the <a rel="external" href="http://simpleinjector.codeplex.com" title="Simple Injector">Simple Injector</a>, the registration looks like this:</p><pre class="cs" language="csharp" customtypes="AppDomain Consumer Container Controller ValidationQueryHandlerDecorator DebuggerStepThrough FakeFailingUserQueries FakeUserServicesUserQueries FindUsersBySearchTextQuery FindUsersBySearchTextQueryHandler GetCurrentTimeQuery GetCurrentUserIdQuery GetHighUsageUsersQuery GetRecentOrdersForLoggedInUserQuery GetUsersByRolesQuery IQuery IQueryExecuter IQueryHandler IQueryProcessor IServiceProvider IUserQueries NorthwindUnitOfWork QueryExecuter QueryProcessor Required StringLength User UserController UserInfo UserQueryHandlers ValidationContext Validator" customvaluetypes="PutYourCustomValueTypesHere">container.RegisterManyForOpenGeneric(typeof(IQueryHandler&lt;,&gt;),<br />    AppDomain.CurrentDomain.GetAssemblies());</pre><p>This line of code saves you from having to change the DI configuration when you add new query handlers to the system. They will be picked up automatically.</p><p>With this in place we can now add cross-cutting concerns such as logging, audit trailing, and what have you. Or let&rsquo;s say you want to decorate properties of the query objects with Data Annotations attributes, to be able to do validation. This might look like this:</p><pre class="cs" language="csharp" customtypes="AppDomain Consumer Container Controller ValidationQueryHandlerDecorator DebuggerStepThrough FakeFailingUserQueries FakeUserServicesUserQueries FindUsersBySearchTextQuery FindUsersBySearchTextQueryHandler GetCurrentTimeQuery GetCurrentUserIdQuery GetHighUsageUsersQuery GetRecentOrdersForLoggedInUserQuery GetUsersByRolesQuery IQuery IQueryExecuter IQueryHandler IQueryProcessor IServiceProvider IUserQueries NorthwindUnitOfWork QueryExecuter QueryProcessor Required StringLength User UserController UserInfo UserQueryHandlers ValidationContext Validator" customvaluetypes="PutYourCustomValueTypesHere">public class FindUsersBySearchTextQuery : IQuery&lt;User[]&gt;<br />{<br />    // Required and StringLength are attributes from the<br />    // System.ComponentModel.DataAnnotations assembly.<br />    [Required]<br />    [StringLength(1)]<br />    public string SearchText { get; set; }<br /> <br />    public bool IncludeInactiveUsers { get; set; }<br />}</pre><p>Because we modeled our query handlers around a single <span class="type">IQueryHandler</span><span class="code">&lt;TQuery, TResult&gt;</span> interface, we can define a simple decorator that allows us to do this:</p><pre class="cs" language="csharp" customtypes="AppDomain Consumer Container Controller ValidationQueryHandlerDecorator DebuggerStepThrough FakeFailingUserQueries FakeUserServicesUserQueries FindUsersBySearchTextQuery FindUsersBySearchTextQueryHandler GetCurrentTimeQuery GetCurrentUserIdQuery GetHighUsageUsersQuery GetRecentOrdersForLoggedInUserQuery GetUsersByRolesQuery IQuery IQueryExecuter IQueryHandler IQueryProcessor IServiceProvider IUserQueries NorthwindUnitOfWork QueryExecuter QueryProcessor Required StringLength User UserController UserInfo UserQueryHandlers ValidationContext Validator" customvaluetypes="PutYourCustomValueTypesHere">public class ValidationQueryHandlerDecorator&lt;TQuery, TResult&gt;<br />    : IQueryHandler&lt;TQuery, TResult&gt;<br />    where TQuery : IQuery&lt;TResult&gt;<br />{<br />    private readonly IServiceProvider provider;<br />    private readonly IQueryHandler&lt;TQuery, TResult&gt; decorated;<br /> <br />    [DebuggerStepThrough]<br />    public ValidationQueryHandlerDecorator(<br />        Container container,<br />        IQueryHandler&lt;TQuery, TResult&gt; decorated)<br />    {<br />        this.provider = container;<br />        this.decorated = decorated;<br />    }<br /> <br />    [DebuggerStepThrough]<br />    public TResult Handle(TQuery query)<br />    {<br />        this.Validate(query);<br />        return this.decorated.Handle(query);<br />    }<br /> <br />    [DebuggerStepThrough]<br />    private void Validate(TQuery query)<br />    {<br />        var validationContext =<br />            new ValidationContext(query, this.provider, null);<br /> <br />        Validator.ValidateObject(query, validationContext);<br />    }<br />}</pre><p>This decorator allows us to validate query objects before they get sent to their handler, without us having to change a single line of code in the application, expect of course the following single line of code in our start-up path:</p><pre class="cs" language="csharp" customtypes="AppDomain Consumer Container Controller ValidationQueryHandlerDecorator DebuggerStepThrough FakeFailingUserQueries FakeUserServicesUserQueries FindUsersBySearchTextQuery FindUsersBySearchTextQueryHandler GetCurrentTimeQuery GetCurrentUserIdQuery GetHighUsageUsersQuery GetRecentOrdersForLoggedInUserQuery GetUsersByRolesQuery IQuery IQueryExecuter IQueryHandler IQueryProcessor IServiceProvider IUserQueries NorthwindUnitOfWork QueryExecuter QueryProcessor Required StringLength User UserController UserInfo UserQueryHandlers ValidationContext Validator" customvaluetypes="PutYourCustomValueTypesHere">container.RegisterOpenGenericDecorator(typeof(IQueryHandler&lt;,&gt;),<br />    typeof(ValidationQueryHandlerDecorator&lt;,&gt;));</pre><p>The <span class="code">RegisterOpenGenericDecorator</span> extension method is part of the SimpleInjector.Extensions.dll, which is part of the <a rel="external" href="simpleinjector.codeplex.com/releases/" title="Simple Injector - Latest release">download on CodePlex</a> and available as <a rel="external" href="nuget.org/packages?q=simpleinjector.extensions" title="NuGet - SimpleInjector.Extensions">separate NuGet package</a>. </p><p>I&rsquo;ve been using this model for some time now and there is one thing that struck me quickly, which is that in fact everything in the system is a query (or a command). If we want we can model every single operation as a query (or command). Do we really want to do this? No, definitely not, because this doesn&rsquo;t always result in the most readable code. Take a look at this example:</p><pre class="cs" language="csharp" customtypes="AppDomain Consumer Container Controller ValidationQueryHandlerDecorator DebuggerStepThrough FakeFailingUserQueries FakeUserServicesUserQueries FindUsersBySearchTextQuery FindUsersBySearchTextQueryHandler GetCurrentTimeQuery GetCurrentUserIdQuery GetHighUsageUsersQuery GetRecentOrdersForLoggedInUserQuery GetUsersByRolesQuery IQuery IQueryExecuter IQueryHandler IQueryProcessor IServiceProvider IUserQueries NorthwindUnitOfWork QueryExecuter QueryProcessor Required StringLength User UserController UserInfo UserQueryHandlers ValidationContext Validator" customvaluetypes="PutYourCustomValueTypesHere">public IQueryable&lt;Order&gt; Handle(<br />    GetRecentOrdersForLoggedInUserQuery query)<br />{<br />    int currentUserId =<br />        this.queryProcessor.Execute(new GetCurrentUserIdQuery());<br /> <br />    DateTime currentTime =<br />        this.queryProcessor.Execute(new GetCurrentTimeQuery());<br /> <br />    return<br />        from order in db.Orders<br />        where order.User.Id == currentUserId<br />        where order.CreateDate &gt;= currentTime.AddDays(-30)<br />        select order;<br />}</pre><p>Isn&rsquo;t that nice? This query method delegates part of its work of to two other queries, which is fine by itself of course. However, using queries for retrieving really simple things does give too much coding overhead. In this case I rather use <span class="type">IUserContext</span> and <span class="type">ITimeProvider</span> services. This makes the method shorter and easier to read:</p><pre class="cs" language="csharp" customtypes="AppDomain Consumer Container Controller ValidationQueryHandlerDecorator DebuggerStepThrough FakeFailingUserQueries FakeUserServicesUserQueries FindUsersBySearchTextQuery FindUsersBySearchTextQueryHandler GetCurrentTimeQuery GetCurrentUserIdQuery GetHighUsageUsersQuery GetRecentOrdersForLoggedInUserQuery GetUsersByRolesQuery IQuery IQueryExecuter IQueryHandler IQueryProcessor IServiceProvider IUserQueries NorthwindUnitOfWork QueryExecuter QueryProcessor Required StringLength User UserController UserInfo UserQueryHandlers ValidationContext Validator" customvaluetypes="PutYourCustomValueTypesHere">public IQueryable&lt;Order&gt; Handle(<br />    GetRecentOrdersForLoggedInUserQuery query)<br />{<br />    return<br />        from order in db.Orders<br />        where order.User.Id == this.userContext.UserId<br />        where order.CreateDate &gt;=<br />            this.timeProvider.Now.AddDays(-30)<br />        select order;<br />}</pre><p>So where do we draw the line between using an <span class="type">IQuery</span><span class="code">&lt;TResult&gt;</span> and specifying an explicit separate service interface? I can&rsquo;t really give any hard guidelines on that. A little bit of intuition and experience will have to guide you here. However, I think when it just returns a (cached) value without really hitting an external resource, such as the file system, web service, or database, and it doesn&rsquo;t contain any parameters, and when you&rsquo;re very sure you never want to wrap it with a decorator (no performance measuring, no audit trailing, no asynchronous processing); it&rsquo;s pretty safe to define it as a specific service interface.</p><p>That&rsquo;s how I roll on the query side of my architecture.</p>
		]]></content>
		<author>
			<name>Steven</name>
		</author>
	</entry>
	
	
	
	<entry>
		<title>Meanwhile… on the command side of my architecture</title>
		<link rel="alternate" type="text/html" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=91" />
		<updated>2012-04-14T22:34:00+02:00</updated>
		<published>2011-12-11T23:08:00+02:00</published>
		<id>tag:pivotpowered,2012:NETJunkie.91</id>
		<link rel="related" type="text/html" href=""  />
		<summary type="text">This article describes how one simple interface can make the design of your application so much cleaner and flexible than you ever thought was possible.</summary>
        <content type="html" xml:lang="en" xml:base="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=91"><![CDATA[
                This article describes how one simple interface can make the design of your application so much cleaner and flexible than you ever thought was possible.<p style="padding-left: 40px"><em>If you find this article interesting, you should also read my follow up: <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=92" title=".NET Junkie - Meanwhile&hellip; on the query side of my architecture">Meanwhile... on the query side of my architecture</a>.</em></p><p>Since writing applications in .NET, I've been separating operations that mutate state (of the database mostly) and operations that return data. Basically, this is what the <a rel="external" href="http://en.wikipedia.org/wiki/Command-query_separation" title="Wikipedia - Command-query separation principle">Command-query separation principle</a> is all about. Over the years the design I used has evolved. Triggered by a former colleague of mine, I started to use the <a rel="external" href="http://en.wikipedia.org/wiki/Command_pattern" title="Wikipedia - Command pattern">Command Pattern</a> about four years back as the design around state mutations in my business layer. We called them business commands, since a single command would represents an atomic business operation, or single <a rel="external" href="http://en.wikipedia.org/wiki/Use_case" title="Wikipedia - Use case">use case</a>.</p><p>This model has worked well for the last couple of years, and in a sense, I'm still using it today. However the design was around command classes that contained both properties to hold the data and an <span class="code">Execute()</span> method that would start that operation. The last few years however, the projects I participated in, increased in complexity and I started doing things like <a rel="external" href="http://en.wikipedia.org/wiki/Test-driven_development" title="Wikipedia - TDD">Test Driven Development</a> and <a rel="external" href="http://en.wikipedia.org/wiki/Dependency_injection" title="Wikipedia - Dependency injection">Dependency Injection</a> (DI). I soon started to notice the flaws in this design (DI has this tendency of exposing violations of the <a rel="external" href="http://en.wikipedia.org/wiki/SOLID" title="Wikipedia - SOLID object oriented design principles">SOLID</a> principles) and that design hindered me in the maintainability of these applications.</p><p>The design was always based around some abstract <span class="type">Command</span> base class that contained all logic for handling transactions, re-executing commands after a deadlock occurred, measuring performance, security checks, and such. This base class was a big <a rel="external" href="http://en.wikipedia.org/wiki/Code_smell" title="Wikipedia - Code smell">code smell</a>, because it acted as some sort of <a rel="external" href="http://en.wikipedia.org/wiki/God_object" title="Wikipedia - God object">God Object</a> having many responsibilities. Furthermore, the design where data and behavior were mixed, made it very hard to fake that logic during testing, since that consumer would typically new up a command instance and call <span class="code">Execute()</span> directly on that instance, as shown in the following example:</p><pre class="cs" language="csharp" customtypes="Controller Address sController CustomerController DbException  DeadlockRetryCommandHandlerDecorator EntityFrameworkUnitOfWork ICommandHandler MoveCustomerCommand MoveCustomerCommandHandler Thread TransactionCommandHandlerDecorator TransactionScope UnitOfWork" customvaluetypes="PutYourCustomValueTypesHere">var command = new MoveCustomerCommand<br />{<br />    CustomerId = customerId,<br />    NewAddress = address<br />};<br /><br />command.Execute();<br /></pre></p><p>I tried to solve this problem by injecting commands in the constructor (constructor injection) of a consumer, but this was awkward to say the least. In that case, the consumer had to set all the properties of an object it got from the outside, and that still didn't really solve the problem of abstracting away the command elegantly, since for every command I would have to define a fake command in the test suite and it still left me with a big complicated base class that was hard to extend.</p><p>This finally lead to a design that I&rsquo;ve seen others use, but never saw the benefits of. In this design data and behavior is separated. For each business operation I now use a simple data container, which name ends with 'Command', such as the following:</p> <pre class="cs" language="csharp" customtypes="Controller Address sController CustomerController DbException  DeadlockRetryCommandHandlerDecorator EntityFrameworkUnitOfWork ICommandHandler MoveCustomerCommand MoveCustomerCommandHandler Thread TransactionCommandHandlerDecorator TransactionScope UnitOfWork" customvaluetypes="PutYourCustomValueTypesHere">public class MoveCustomerCommand<br />{<br />    public int CustomerId { get; set; }<br /> <br />    public Address NewAddress { get; set; }<br />}</pre><p>The actual logic gets its own class, which name ends with 'CommandHandler':</p><pre class="cs" language="csharp" customtypes="Controller Address sController CustomerController DbException  DeadlockRetryCommandHandlerDecorator EntityFrameworkUnitOfWork ICommandHandler MoveCustomerCommand MoveCustomerCommandHandler Thread TransactionCommandHandlerDecorator TransactionScope UnitOfWork" customvaluetypes="PutYourCustomValueTypesHere">public class MoveCustomerCommandHandler<br />{<br />    private readonly UnitOfWork db;<br /><br />    public MoveCustomerCommandHandler(UnitOfWork db,<br />        [Other dependencies here])<br />    {<br />        this.db = db;<br />    }<br /> <br />    public virtual void Handle(MoveCustomerCommand command)<br />    {<br />        // TODO: Logic here<br />    }<br />}<br /></pre></p><p>This design immediately wins us a lot, since a command handler can be injected into a consumer, which can simply new up a command. Because the command only contains data, there is never a reason anymore to fake the command itself during testing. Here&rsquo;s an example of how a consumer can use that command and handler:</p> <pre class="cs" language="csharp" customtypes="Controller Address sController CustomerController DbException  DeadlockRetryCommandHandlerDecorator EntityFrameworkUnitOfWork ICommandHandler MoveCustomerCommand MoveCustomerCommandHandler Thread TransactionCommandHandlerDecorator TransactionScope UnitOfWork" customvaluetypes="PutYourCustomValueTypesHere">public class CustomerController : Controller<br />{<br />    private readonly MoveCustomerCommandHandler handler;<br /> <br />    public CustomerController(MoveCustomerCommandHandler handler)<br />    {<br />        this.handler = handler;<br />    }<br /> <br />    public void MoveCustomer(int customerId, Address newAddress)<br />    {<br />        var command = new MoveCustomerCommand<br />        {<br />            CustomerId = customerId,<br />            NewAddress = newAddress<br />        };<br /> <br />        this.handler.Handle(command);<br />    }<br />}<br /></pre><p>There is however, still a problem with this design. Although every handler class has a single (public) method (and therefore adheres the <a rel="external" href="http://en.wikipedia.org/wiki/Interface_segregation_principle" title="Wikipedia - Interface Segregation Principle">Interface Segregation Principle</a>), all handlers define their own interface (there is no common interface), which makes it hard to extend those handlers with new features and add cross-cutting concerns. Say for instance that we would like to measure the time it takes to execute every command and log this to the database. Howe would we do this? It would either involve changing each and every command, or moving that logic to a base class. Moving this to the base class is not ideal, because in no time the base class would contain lots and lots of such features, growing out of control (which I&rsquo;ve seen happening). Besides, this would make it hard to enable/disable such behavior for certain types (or instances) of command handlers, since this would involve in adding conditional logic into the base class, making it even more complicated.</p><p>All these problems can be solved elegantly by letting all handlers inherit from a single generic interface:</p> <pre class="cs" language="csharp" customtypes="Controller Address sController CustomerController DbException  DeadlockRetryCommandHandlerDecorator EntityFrameworkUnitOfWork ICommandHandler MoveCustomerCommand MoveCustomerCommandHandler Thread TransactionCommandHandlerDecorator TransactionScope UnitOfWork" customvaluetypes="PutYourCustomValueTypesHere">public interface ICommandHandler&lt;TCommand&gt;<br />{<br />    void Handle(TCommand command);<br />}<br /></pre><p>Using this interface, the <span class="type">MoveCustomerCommandHandler</span> would now look like this:</p> <pre class="cs" language="csharp" customtypes="Controller Address sController CustomerController DbException  DeadlockRetryCommandHandlerDecorator EntityFrameworkUnitOfWork ICommandHandler MoveCustomerCommand MoveCustomerCommandHandler Thread TransactionCommandHandlerDecorator TransactionScope UnitOfWork" customvaluetypes="PutYourCustomValueTypesHere">// Exactly the same as before, but now with the interface.<br />public class MoveCustomerCommandHandler<br />    : ICommandHandler&lt;MoveCustomerCommand&gt;<br />{<br />    private readonly UnitOfWork db;<br /><br />    public MoveCustomerCommandHandler(UnitOfWork db,<br />        [Other dependencies here])<br />    {<br />        this.db = db;<br />    }<br /> <br />    public void Handle(MoveCustomerCommand command)<br />    {<br />        // TODO: Logic here<br />    }<br />}<br /></pre><p>Important benefit of this interface is that it allows us to let the consumers depend on that single abstraction, not on a concrete command handler implementation:</p> <pre class="cs" language="csharp" customtypes="Controller Address sController CustomerController DbException  DeadlockRetryCommandHandlerDecorator EntityFrameworkUnitOfWork ICommandHandler MoveCustomerCommand MoveCustomerCommandHandler Thread TransactionCommandHandlerDecorator TransactionScope UnitOfWork" customvaluetypes="PutYourCustomValueTypesHere">// Again, same implementation as before, but now we depend<br />// upon the ICommandHandler abstraction.<br />public class CustomerController : Controller<br />{<br />    private ICommandHandler&lt;MoveCustomerCommand&gt; handler;<br /> <br />    public CustomerController(<br />        ICommandHandler&lt;MoveCustomerCommand&gt; handler)<br />    {<br />        this.handler = handler;<br />    }<br /> <br />    public void MoveCustomer(int customerId, Address newAddress)<br />    {<br />        var command = new MoveCustomerCommand<br />        {<br />            CustomerId = customerId,<br />            NewAddress = newAddress<br />        };<br /> <br />        this.handler.Handle(command);<br />    }<br />}<br /></pre><p>What does adding an interface help us in this case? Well frankly, a lot! Since nobody depends directly on the implementation, we can now replace those handlers with something else (as long as it implements that interface). Setting testability aside, look for instance at this generic class:</p> <pre class="cs" language="csharp" customtypes="Controller Address sController CustomerController DbException  DeadlockRetryCommandHandlerDecorator EntityFrameworkUnitOfWork ICommandHandler MoveCustomerCommand MoveCustomerCommandHandler Thread TransactionCommandHandlerDecorator TransactionScope UnitOfWork" customvaluetypes="PutYourCustomValueTypesHere">public class TransactionCommandHandlerDecorator&lt;TCommand&gt;<br />    : ICommandHandler&lt;TCommand&gt;<br />{<br />    private readonly ICommandHandler&lt;TCommand&gt; decorated;<br /> <br />    public TransactionCommandHandlerDecorator(<br />        ICommandHandler&lt;TCommand&gt; decorated)<br />    {<br />        this.decorated = decorated;<br />    }<br /> <br />    public void Handle(TCommand command)<br />    {<br />        using (var scope = new TransactionScope())<br />        {<br />            this.decorated.Handle(command);<br /> <br />            scope.Complete();<br />        }<br />    }<br />}<br /></pre><p>This class wraps an <span class="type">ICommandHandler</span><span class="code">&lt;TCommand&gt;</span> instance, but also implements <span class="type">ICommandHandler</span><span class="code">&lt;TCommand&gt;</span>. It is an implementation of the <a rel="external" href="http://en.wikipedia.org/wiki/Decorator_pattern" title="Wikipedia - Decorator pattern">Decorator pattern</a>. This very simple class allows us to add transaction support to all command handlers. For instance, instead of injecting a <span class="type">MoveCustomerCommandHandler</span> directly into the <span class="type">CustomerController</span>, we can inject the following:</p> <pre class="cs" language="csharp" customtypes="Controller Address sController CustomerController DbException  DeadlockRetryCommandHandlerDecorator EntityFrameworkUnitOfWork ICommandHandler MoveCustomerCommand MoveCustomerCommandHandler Thread TransactionCommandHandlerDecorator TransactionScope UnitOfWork" customvaluetypes="PutYourCustomValueTypesHere">var handler =<br />    new TransactionCommandHandlerDecorator&lt;MoveCustomerCommand&gt;(<br />        new MoveCustomerCommandHandler(<br />            new EntityFrameworkUnitOfWork(connectionString),<br />            // Inject other dependencies for the handler here<br />        )<br />    );<br /> <br />// Inject the handler into the controller&rsquo;s constructor.<br />var controller = new CustomerController(handler);<br /></pre><p>Nice about this is that this single decorator class (containing just 5 lines of code) could be reused for all command handlers in the system. Downside of this is of course that it would take a lot of boilerplate code to wire this up for all classes that depend on a command handler, but at least the rest of the application is oblivious to this change. Of course, in reality, when you have more than a couple consumers of such handler, you should start using <a rel="external" href="http://simpleinjector.codeplex.com" title="Simple Injector">a Dependency Injection framework</a>, since such framework can automate this wiring for you and it will help you in making even this part of your application maintainable.</p><p>If you're still not convinced, let's define another decorator:</p><pre class="cs" language="csharp" customtypes="Controller Address sController CustomerController DbException  DeadlockRetryCommandHandlerDecorator EntityFrameworkUnitOfWork ICommandHandler MoveCustomerCommand MoveCustomerCommandHandler Thread TransactionCommandHandlerDecorator TransactionScope UnitOfWork" customvaluetypes="PutYourCustomValueTypesHere">public class DeadlockRetryCommandHandlerDecorator&lt;TCommand&gt;<br />    : ICommandHandler&lt;TCommand&gt;<br />{<br />    private readonly ICommandHandler&lt;TCommand&gt; decorated;<br /> <br />    public DeadlockRetryCommandHandlerDecorator(<br />        ICommandHandler&lt;TCommand&gt; decorated)<br />    {<br />        this.decorated = decorated;<br />    }<br /> <br />    public void Handle(TCommand command)<br />    {<br />        this.HandleWithCountDown(command, 5);<br />    }<br /> <br />    private void HandleWithCountDown(TCommand command,<br />        int count)<br />    {<br />        try<br />        {<br />            this.decorated.Handle(command);<br />        }<br />        catch (Exception ex)<br />        {<br />            if (count &lt;= 0 || !IsDeadlockException(ex))<br />                throw;<br /> <br />            Thread.Sleep(300);<br /> <br />            this.HandleWithCountDown(command, count - 1);<br />        }<br />    }<br /> <br />    private static bool IsDeadlockException(Exception ex)<br />    {<br />        while (ex != null)<br />        {<br />            if (ex is DbException &amp;&amp; <br />                ex.Message.Contains(&quot;deadlock&quot;))<br />            {<br />                return true;<br />            }<br /> <br />            ex = ex.InnerException;<br />        }<br /> <br />        return false;<br />    }<br />}<br /></pre><p>I think this class speaks for itself. Although this class contains more code than the previous, it's still just 14 lines of code. It allows the execution of a command to be re-executed for 5 times in case a database deadlock occurred, before it lets the thrown exception bubble up. Again, we can use this class by wrapping the previous decorator, as follows:</p><pre class="cs" language="csharp" customtypes="Controller Address sController CustomerController DbException  DeadlockRetryCommandHandlerDecorator EntityFrameworkUnitOfWork ICommandHandler MoveCustomerCommand MoveCustomerCommandHandler Thread TransactionCommandHandlerDecorator TransactionScope UnitOfWork" customvaluetypes="PutYourCustomValueTypesHere">var handler =<br />    new DeadlockRetryCommandHandlerDecorator&lt;MoveCustomerCommand&gt;(<br />        new TransactionCommandHandlerDecorator&lt;MoveCustomerCommand&gt;(<br />            new MoveCustomerCommandHandler(<br />                new EntityFrameworkUnitOfWork(connectionString),<br />                // Inject other dependencies for the handler here<br />            )<br />        )<br />    );<br /><br />var controller = new CustomerController(handler);<br /></pre><p>By the way, did you notice how both decorators are completely focused? They each have just a single responsibility. This makes them easy to understand, easy to change, which is what the <a rel="external" href="http://en.wikipedia.org/wiki/Single_responsibility_principle" title="Wikipedia - Single responsibility principle">Single Responsibility Principle</a> is about.</p><p>Of course the correctness of the system now depends on the correct wiring of these dependencies, since wrapping the deadlock retry behavior INSIDE the transaction behavior might lead to unexpected behavior (since a database deadlock typically has the effect of the database rolling back the transaction, while leaving the connection open), but this is solely a problem for the part of the application that wires this all together. Again, the rest of the application is oblivious.</p><p>Of course I could go on giving examples of decorators, such as a decorator that validate commands before they get executed, checks the user authorization, measures the performance of the command, logs an audit trail of the command, or last but not least a decorator that queues the command to be processed in a different process.</p><p style="padding-left: 40px; font-size: smaller"><em>&lt;BackgroundStory&gt;This last one is a very interesting one. Years back I worked on an application that queued commands in the database. We wrote business processes (commands by themselves) that sometimes queued dozens of other (sub) commands, which allowed them to be processed in parallel by different processes (multiple Windows services on different machines). These commands did things like sending mails or heavy stuff such as generating PDF documents (that would be merged later on by another command, and sending those merged documents to a printer by yet another command). The queue was transactional, which allowed us to -in a sense- send mails and upload files to FTP in a transactional manner. However, We didn't use dependency injection back then, which made everything so much harder (if only we knew).&lt;/BackgroundStory&gt;</em></p><p>Because commands are simple data containers without behavior, it is very easy to serialize them (using the <span class="type">XmlSerializer</span> for instance) or send them over the wire (using WCF for instance), which makes it not only easy to queue them for later processing, but also makes it very easy to log them as an audit trail, which is yet another reason to separate data and behavior. All these features can be added, without changing a single line of code in the application (except perhaps a few lines in the start-up path of the application).</p><p>And it was just one simple <span class="type">ICommandHandler</span><span class="code">&lt;TCommand&gt;</span> interface that made this all possible. While it may seem complex at first, when you get the hang of this (together with dependency injection), well... the possibilities are endless. And even when you think you don&rsquo;t need all of this, this design allows you to make many unforeseen changes to the system, without much trouble. Still we can hardly argue a system with this design is over-engineered, since we just put every operation in its own class and put a generic interface on it. It&rsquo;s hard to over-engineer that, because even really small systems benefit from <a rel="external" href="http://en.wikipedia.org/wiki/Separation_of_concerns" title="Wikipedia - Separation of concerns">separating concerns</a>.</p><p>Still, this doesn't mean things can&rsquo;t get complicated sometimes. Doing the correct wiring of all those dependencies, and writing and adding the decorators in the right order can sometimes be challenging. But still, this complexity is focused in a single part of the application (the start-up path a.k.a. <a rel="external" href="http://blog.ploeh.dk/2011/07/28/CompositionRoot.aspx" title="Mark Seemann's blog - Composition Root">Composition Root</a>), which leaves the rest of the application unaware and unaffected of this. You hardly ever have to change the rest of the application for this, which is what the <a rel="external" href="http://en.wikipedia.org/wiki/Open/closed_principle" title="Wikipedia - Open/closed principle">Open/Closed Principle</a> is all about.</p><p>By the way, you probably think the way I created all those decorators around a single command handler is rather awkward, and imagined the big ball of mud that it would become after we got a few dozen of command handlers. Yes, you would be probably right that this doesn&rsquo;t scale well. But as I said, this is where DI containers come in. For instance, when using the <a rel="external" href="http://simpleinjector.codeplex.com" title="Simple Injector">Simple Injector</a>, registering all command handlers in the system can be done with <a rel="external" href="http://simpleinjector.codeplex.com/wikipage?title=Advanced-scenarios#Registration_Of_Open_Generic_Types" title="Simple Injector - Advanced scenarios - Registration of open generic types">a single line of code</a>. After that, registering a decorator is also <a rel="external" href="http://simpleinjector.codeplex.com/wikipage?title=Advanced-scenarios#Generic_Decorators" title="Simple Injector - documentation - Advanced scenarios - Generic Decorators">a single line</a>. Here is an example of the configuration when using the Simple Injector: </p><pre class="cs" language="csharp" customtypes="Controller Address sController CustomerController DbException  DeadlockRetryCommandHandlerDecorator EntityFrameworkUnitOfWork ICommandHandler MoveCustomerCommand MoveCustomerCommandHandler Thread TransactionCommandHandlerDecorator TransactionScope UnitOfWork Container" customvaluetypes="PutYourCustomValueTypesHere">var container = new Container();<br /><br />// Go look in all assemblies and register all implementations<br />// of ICommandHandler&lt;T&gt; by their closed interface:<br />container.RegisterManyForOpenGeneric(typeof(ICommandHandler&lt;&gt;),<br />    AppDomain.CurrentDomain.GetAssemblies());<br /><br />// Decorate each returned ICommandHandler&lt;T&gt; object with an<br />// TransactionCommandHandlerDecorator&lt;T&gt;.<br />container.RegisterOpenGenericDecorator(typeof(ICommandHandler&lt;&gt;),<br />    typeof(TransactionCommandHandlerDecorator&lt;&gt;));<br /><br />// Decorate each returned ICommandHandler&lt;T&gt; object with an<br />// DeadlockRetryCommandHandlerDecorator&lt;T&gt;.<br />container.RegisterOpenGenericDecorator(typeof(ICommandHandler&lt;&gt;),<br />    typeof(DeadlockRetryCommandHandlerDecorator&lt;&gt;));<br /></pre><p>No matter how many handlers you add to the system, this few lines of code won&rsquo;t change, which underlines the true power of what DI containers can do for you. After you made your application maintainable by applying the SOLID principles, a good DI container will ensure that also the startup path of your application stays maintainable.</p><p>This is how I roll on the command side of my architecture.</p><p>If you found this article interesting, you should also read my follow up: <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=92" title=".NET Junkie - Meanwhile&hellip; on the query side of my architecture">Meanwhile... on the query side of my architecture</a> and take a look how to <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=93" title=".NET Junkie - Returning data from command handlers">return data from command handlers</a>.</p>
		]]></content>
		<author>
			<name>Steven</name>
		</author>
	</entry>
	
	
	
	<entry>
		<title>Adding Covariance and Contravariance to the Simple Injector</title>
		<link rel="alternate" type="text/html" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=90" />
		<updated>2012-02-18T16:39:00+02:00</updated>
		<published>2011-10-01T17:08:00+02:00</published>
		<id>tag:pivotpowered,2012:NETJunkie.90</id>
		<link rel="related" type="text/html" href=""  />
		<summary type="text">A few weeks back I read this question on Stackoverflow. The question was about applying covariance / contravariance (or variance for short) to the Autofac dependency injection container. The question triggered me to think about variance support in the Simple Injector.  I was wondering whether special changes were needed to the core  framework to allow this. However, it didn't take me long to realize that  enabling variance is actually pretty easy for anyone using the Simple  Injector. The prerequisites are a proper application design and .NET  4.0.</summary>
        <content type="html" xml:lang="en" xml:base="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=90"><![CDATA[
                A few weeks back I read <a rel="external" href="http://stackoverflow.com/questions/7010236/customizing-autofacs-component-resolution-issue-with-generic-co-contravarianc" title="Stackoverflow - Customizing Autofac's component resolution / Issue with generic co-/contravariance">this question</a> on <a rel="external" href="http://www.stackoverflow.com/" title="Stackoverflow">Stackoverflow</a>. The question was about applying <a rel="external" href="http://msdn.microsoft.com/en-us/library/dd799517.aspx" title="MSDN - Covariance and Contravariance in Generics">covariance / contravariance</a> (or variance for short) to the <a rel="external" href="http://code.google.com/p/autofac/" title="Autofac">Autofac</a> dependency injection container. The question triggered me to think about variance support in the <a rel="external" href="http://simpleinjector.codeplex.com/" title="Simple Injector">Simple Injector</a>.  I was wondering whether special changes were needed to the core  framework to allow this. However, it didn't take me long to realize that  enabling variance is actually pretty easy for anyone using the Simple  Injector. The prerequisites are a proper application design and .NET  4.0.<p><img src="http://www.cuttingedge.it/blogs/steven/images/nurse1.jpg" style="float:right;margin-left:10px;margin-bottom:5px;border:1px solid" title="" alt="" class="pivot-image" />What's nice about the Simple Injector IMO, is that although it has a small API, it has a few very cleverly chosen extensibility points, which make it possible to add almost every imaginable advanced scenario. Both the SimpleInjector.Extensions.dll (which runs on top of the core library <em>without any access to the internals</em>) and the examples in the <a rel="external" href="http://simpleinjector.codeplex.com/wikipage?title=Advanced-scenarios" title="Advanced scenarios with the Simple Injector">advanced scenarios section</a> on <a rel="external" href="http://www.codeplex.com" title="Codeplex">CodePlex</a>, prove this point.</p><p>Although the extensibility points of the Simple Injector are fine, adding out of the box support for variance still isn't possible. It is not a limitation of the Simple Injection however; it is the possible variety of application designs that makes it impossible to come with a single solution that works for everybody.</p><p>For instance, what should the container do when an unregistered (variant) service type is requested? It should probably go look for a registration that is assignable from that requested type. But what if there are multiple compatible registrations? Should the container throw an exception? Should the container use the registration that is closest in the inheritance hierarchy to the requested type? And what to do when there are multiple types that are just as close? Or should the container return a list of all compatible registrations (possibly wrapped in a <a rel="external" href="http://en.wikipedia.org/wiki/Composite_pattern" title="Wikipedia - Composite Design Pattern">composite</a>). And should this behavior hold for all types in the container, should it just be enabled for a set or types, or should the behavior differ per registration?</p><p>In the end, it is the application designer / developer that must decide what the correct behavior is, and because of this, it is impossible for a framework to pick the correct behavior. Because of this, I'm not adding such feature to the framework or even the Extensions.dll. But as I said, it is pretty easy to do it yourself, and I will describe how to in the rest of this article. </p><p>If you are still reading this, I assume you are one of the few who needs variance support -or- you are (like me) a geek who likes to think about this sort of stuff, just because it is fun :-). Below I'll describe three scenarios that I think are the most common ones to appear when you need to apply variance. Below I'll define an <span class="type">IEventHandler</span><span class="code">&lt;TEvent&gt;</span> interface with supporting classes that I'll be using as example for the rest of this article.</p><p>Event handlers are a good example to show case variance support, because they are likely part of the application design that would benifit from it. Event handlers are used more and more in common architecture. <a rel="external" href="http://abdullin.com/cqrs" title="Command and Query Responsibility Segregation">CQRS</a> is good example of an architecture that uses them extensively. When a single event is raised (by a command for instance), it seems reasonable to set up the application in such way that multiple event handlers would trigger that event. But to go a step further, imagine the definition of a <span class="type">CustomerMovedAbroadEvent</span> that inherits from a <span class="type">CustomerMovedEvent</span>. An event handler that handles a <span class="type">CustomerMovedEvent</span> can technically also handle a <span class="type">CustomerMovedAbroadEvent</span> (if it doesn't work, we would be breaking the <a rel="external" href="http://en.wikipedia.org/wiki/Liskov_substitution_principle" title="Wikipedia - Liskov substitution principle">Liskov substitution principle</a> anyway). Not only would we want to have multiple event handlers to handle a single <span class="type">CustomerMovedEvent</span> event, we also want those same handlers to handle a <span class="type">CustomerMovedAbroadEvent</span> event. For this scenario we need to add contravariance support (or atleast, contravariance will make it much easier to implement this).</p><p>The next code snippet shows a <span class="type">CustomerMovedEvent</span> class with two derived classes: <span class="type">CustomerMovedAbroadEvent</span> and <span class="type">SpecialCustomerMovedEvent</span>. For simplicity I removed all properties. These event classes typically contain just data (<a rel="external" href="http://martinfowler.com/eaaCatalog/dataTransferObject.html" title="Data Transformation Object">DTO</a>) and no behavior (separating data and behavior is an important concept when it comes to applying dependency injection). Behavior is defined in event handlers, all implementing the generic <span class="type">IEventHandler</span><span class="code">&lt;</span><span class="keyword">in</span><span class="code"> TEvent&gt;</span> interface. Note the C# 4.0 <span class="keyword">in</span> keyword in the <span class="type">IEventHandler</span><span class="code">&lt;</span><span class="keyword">in</span><span class="code"> TEvent&gt;</span>. This keyword allows variance (contravariance in this case) support.</p><pre class="cs" language="csharp" customtypes="CustomerMovedEvent CustomerMovedAbroadEvent SpecialCustomerMovedEvent IEventHandler CustomerMovedEventHandler NotifyStaffWhenCustomerMovedEventHandler CustomerMovedAbroadEventHandler Container MultipleDispatchEventHandler" customvaluetypes="PutYourCustomValueTypesHere">// Events<br />public class CustomerMovedEvent { }<br /><br />public class CustomerMovedAbroadEvent : CustomerMovedEvent { }<br /><br />public class SpecialCustomerMovedEvent : CustomerMovedEvent { }<br /><br />// Generic handler interface<br />public interface IEventHandler&lt;in TEvent&gt;<br />{<br />    void Handle(TEvent e);<br />}<br /><br />// Handler implementations<br />public class CustomerMovedEventHandler<br />    : IEventHandler&lt;CustomerMovedEvent&gt;<br />{<br />    public void Handle(CustomerMovedEvent e) { ... }<br />}<br /><br />public class NotifyStaffWhenCustomerMovedEventHandler<br />    : IEventHandler&lt;CustomerMovedEvent&gt;<br />{<br />    public void Handle(CustomerMovedEvent e) { ... }<br />}<br /><br />public class CustomerMovedAbroadEventHandler<br />    : IEventHandler&lt;CustomerMovedAbroadEvent&gt;<br />{<br />    public void Handle(CustomerMovedAbroadEvent e) { ... }<br />} <br /></pre><p>The use of the <span class="keyword">in</span> keyword allows us to write the following (compiling) code:</p><pre class="cs" language="csharp" customtypes="CustomerMovedEvent CustomerMovedAbroadEvent SpecialCustomerMovedEvent IEventHandler CustomerMovedEventHandler NotifyStaffWhenCustomerMovedEventHandler CustomerMovedAbroadEventHandler Container MultipleDispatchEventHandler" customvaluetypes="PutYourCustomValueTypesHere">IEventHandler&lt;CustomerMovedEvent&gt; handler =<br />    new CustomerMovedEventHandler();<br /><br />// This next line works because of the 'in' keyword<br />IEventHandler&lt;CustomerMovedAbroadEvent&gt; handler2 = handler;<br /><br />handler2.Handle(new CustomerMovedAbroadEvent());</pre><p>As I explained, event handlers are a good example to show case variance support, because they are a likely part of the application design to need variance support. When raising a single <span class="type">CustomerMovedAbroadEvent</span> event, it seems reasonably to set up the application in such way that all three previously defined event handlers will handle that event.</p><p>Letting multiple event handlers handle a single event is perhaps the most likely and also the nicest scenario to implement. So let's start with this one:</p><h5>Scenario 1<a name="Scenario1" title="Scenario1"></a></h5><h6>Register multiple implementations of the same service type, and resolving multiple assignable services, wrapped in a composite.</h6><p>In this scenario we would like to configure the container in such way that when we request a single event handler for an event, it would return us a composite handler that would forward the event to all assignable event handlers, with the possibility of having multiple handlers that share the exact same service type. In other words, with the previously defined event handlers, the following code should lead to the execution of all three event handlers:</p><pre class="cs" language="csharp" customtypes="CustomerMovedEvent CustomerMovedAbroadEvent SpecialCustomerMovedEvent IEventHandler CustomerMovedEventHandler NotifyStaffWhenCustomerMovedEventHandler CustomerMovedAbroadEventHandler Container MultipleDispatchEventHandler" customvaluetypes="PutYourCustomValueTypesHere">var handler = container<br />    .GetInstance&lt;IEventHandler&lt;CustomerMovedAbroadEvent&gt;&gt;();<br /><br />handler.Handle(new CustomerMovedAbroadEvent());</pre><p>Note that the <span class="type">CustomerMovedEventHandler</span> and the <span class="type">NotifyStaffWhenCustomerMovedEventHandler</span> both handle the <span class="type">CustomerMovedEvent</span> event and they are both assignable from <span class="type">IEventHandler</span><span class="code">&lt;</span><span class="type">CustomerMovedAbroadEvent</span><span class="code">&gt;</span>. In other words, because <span class="type">CustomerMovedAbroadEvent</span> inherits from <span class="type">CustomerMovedEvent</span>, both handlers are able to handle a <span class="type">CustomerMovedAbroadEvent</span>. And of course the container's configuration should enable this.</p><p>By defining a composite event handler that forwards the event to the wrapped handlers, we will be able to hide this design from the application. Consumers will not have to depend on <span class="type">IEnumerable</span><span class="code">&lt;</span><span class="type">IEventHandler</span><span class="code">&lt;</span><span class="code">TEvent&gt;&gt;</span>, but can simply depend on <span class="type">IEventHandler</span><span class="code">&lt;</span><span class="code">TEvent&gt;</span>, which is of course much more convenient.</p><p style="padding-left: 30px"><em>As a general advice, you should prevent injecting lists of services into  consumers if you can, by wrapping that list in a composite, and inject  that composite into consumers. Not wrapping the list in a composite would clutter the application with extra <span class="keyword">foreach</span> loops. While this doesn't seem bad, the consumers shouldn't care, but worse, when we want to change the way the list of services is handled, we will have to go through the complete application, which is a violation of the <a rel="external" href="http://en.wikipedia.org/wiki/Don%27t_repeat_yourself" title="Wikipedia - Don't repeat yourself">DRY principle</a>.</em></p><p>For this to work we need to define the composite. Without the need for any (contra)variance, the simplest way to define such composite, would be something like this:</p><pre class="cs" language="csharp" customtypes="CustomerMovedEvent CustomerMovedAbroadEvent SpecialCustomerMovedEvent IEventHandler CustomerMovedEventHandler NotifyStaffWhenCustomerMovedEventHandler CustomerMovedAbroadEventHandler Container MultipleDispatchEventHandler" customvaluetypes="PutYourCustomValueTypesHere">public sealed class MultipleDispatchEventHandler&lt;TEvent&gt;<br />    : IEventHandler&lt;TEvent&gt;<br />{<br />    private IEnumerable&lt;IEventHandler&lt;TEvent&gt;&gt; handlers;<br /><br />    public MultipleDispatchEventHandler(<br />        IEnumerable&lt;IEventHandler&lt;TEvent&gt;&gt; handlers)<br />    {<br />        this.handlers = handlers;<br />    }<br /><br />    void IEventHandler&lt;TEvent&gt;.Handle(TEvent e)<br />    {<br />        foreach (var handler in this.handlers)<br />        {<br />            handler.Handle(e);<br />        }<br />    }<br />}</pre><p>This class takes a dependency on <span class="type">IEnumerable</span><span class="code">&lt;</span><span class="type">IEventHandler</span><span class="code">&lt;</span><span class="code">TEvent&gt;&gt;</span> and all it does is iterating that collection and calling <span class="code">Handle(e)</span> on each handler in the collection. Note that although it takes a dependency on <span class="type">IEnumerable</span><span class="code">&lt;</span><span class="type">IEventHandler</span><span class="code">&lt;</span><span class="code">TEvent&gt;&gt;</span>, the rest of the application will be oblivious of the <span class="type">IEnumerable</span> and it can simply take a dependency on <span class="type">IEventHandler</span><span class="code">&lt;</span><span class="code">TEvent&gt;</span>. Contravariance will make this class a bit more complex though, but let's get back on that later. Let's first focus on the registration of the event handlers.</p><p>The <span class="type">CustomerMovedEventHandler</span> and <span class="type">NotifyStaffWhenCustomerMovedEventHandler</span> share the same interface: <span class="type">IEventHandler</span><span class="code">&lt;</span><span class="type">CustomerMovedEvent</span><span class="code">&gt;</span>. Unlike other IoC containers, the Simple Injector does not allow implicit registration of multiple implementations of the same type. For instance, the following code snippet will fail at runtime:</p><pre class="cs" language="csharp" customtypes="CustomerMovedEvent CustomerMovedAbroadEvent SpecialCustomerMovedEvent IEventHandler CustomerMovedEventHandler NotifyStaffWhenCustomerMovedEventHandler CustomerMovedAbroadEventHandler Container MultipleDispatchEventHandler" customvaluetypes="PutYourCustomValueTypesHere">container.Register&lt;IEventHandler&lt;CustomerMovedEvent&gt;,<br />    CustomerMovedEventHandler&gt;();<br />container.Register&lt;IEventHandler&lt;CustomerMovedEvent&gt;,<br />    NotifyStaffWhenCustomerMovedEventHandler&gt;();<br /></pre><p>When running this code, it will fail on the second line, because at that point <span class="type">IEventHandler</span><span class="code">&lt;</span><span class="type">CustomerMovedEvent</span><span class="code">&gt;</span> has already been registered. The actual way to do this with the Simple Injector is by using one of the <span class="code">RegisterAll</span> methods (defined in the Extensions.dll), for instance:</p><pre class="cs" language="csharp" customtypes="CustomerMovedEvent CustomerMovedAbroadEvent SpecialCustomerMovedEvent IEventHandler CustomerMovedEventHandler NotifyStaffWhenCustomerMovedEventHandler CustomerMovedAbroadEventHandler Container MultipleDispatchEventHandler" customvaluetypes="PutYourCustomValueTypesHere">container.RegisterAll(typeof(IEventHandler&lt;CustomerMovedEvent&gt;),<br />    new[]<br />    {<br />        typeof(CustomerMovedEventHandler),<br />        typeof(NotifyStaffWhenCustomerMovedEventHandler)<br />    });<br /><br />container.RegisterAll(typeof(IEventHandler&lt;CustomerMovedAbroadEvent&gt;),<br />    new[] { typeof(CustomerMovedAbroadEventHandler) });</pre><p>While this works, I personally prefer to use the following -less verbose- generic overload:</p><pre class="cs" language="csharp" customtypes="CustomerMovedEvent CustomerMovedAbroadEvent SpecialCustomerMovedEvent IEventHandler CustomerMovedEventHandler NotifyStaffWhenCustomerMovedEventHandler CustomerMovedAbroadEventHandler Container MultipleDispatchEventHandler" customvaluetypes="PutYourCustomValueTypesHere">container.RegisterAll&lt;IEventHandler&lt;CustomerMovedEvent&gt;&gt;(<br />    typeof(CustomerMovedEventHandler),<br />    typeof(NotifyStaffWhenCustomerMovedEventHandler));<br /><br />container.RegisterAll&lt;IEventHandler&lt;CustomerMovedAbroadEvent&gt;&gt;(<br />    typeof(CustomerMovedAbroadEventHandler));</pre><p>These <span class="code">RegisterAll</span> methods actually register a single enumerable that calls back into the container on iteration. The actual types won't get registered themselves, but since they are concrete types, the container will be able to create them anyway. As a side note, the code below shows a simplified (and slower) version of what the <span class="code">RegisterAll</span> method actually is doing under the covers:</p><pre class="cs" language="csharp" customtypes="CustomerMovedEvent CustomerMovedAbroadEvent SpecialCustomerMovedEvent IEventHandler CustomerMovedEventHandler NotifyStaffWhenCustomerMovedEventHandler CustomerMovedAbroadEventHandler Container MultipleDispatchEventHandler" customvaluetypes="PutYourCustomValueTypesHere">var types = new[]<br />{<br />    typeof(CustomerMovedEventHandler), <br />    typeof(NotifyStaffWhenCustomerMovedEventHandler)<br />};<br /><br />container.RegisterSingle&lt;IEnumerable&lt;IEventHandler&lt;CustomerMovedEvent&gt;&gt;&gt;(<br />    from type in types<br />    select (IEventHandler&lt;CustomerMovedEvent&gt;)container.GetInstance(type)<br />);</pre><p>Although the <span class="code">RegisterAll</span> overloads are pretty easy to grasp, it gets cumbersome when the application has dozens of event handlers. The same can therefore be achieved in a more automated way by doing batch registration:</p><pre class="cs" language="csharp" customtypes="CustomerMovedEvent CustomerMovedAbroadEvent SpecialCustomerMovedEvent IEventHandler CustomerMovedEventHandler NotifyStaffWhenCustomerMovedEventHandler CustomerMovedAbroadEventHandler Container MultipleDispatchEventHandler" customvaluetypes="PutYourCustomValueTypesHere">container.RegisterManyForOpenGeneric(typeof(IEventHandler&lt;&gt;),<br />    (service, impls) =&gt; container.RegisterAll(service, impls),<br />    AppDomain.CurrentDomain.GetAssemblies());</pre><p>This registration tells the container to go look for all concrete implementations of the <span class="type">IEventHandler</span><span class="code">&lt;</span><span class="code">TEvent&gt;</span> interface in all assemblies of the current App Domain. The other <span class="code">RegisterManyForOpenGeneric</span> overloads that don't take a delegate, directly register the found implementations in the container. Those overloads are however not able to handle service types with multiple registrations (as is the case with the <span class="type">IEventHandler</span><span class="code">&lt;</span><span class="type">CustomerMovedEvent</span><span class="code">&gt;</span>). By supplying a delegate, we inform the container that it should not do the registration itself, but rather delegate that back to the supplied registration callback. For each found service type (in our case <span class="type">IEventHandler</span><span class="code">&lt;</span><span class="type">CustomerMovedEvent</span><span class="code">&gt;</span> and <span class="type">IEventHandler</span><span class="code">&lt;</span><span class="type">CustomerMovedAbroadEvent</span><span class="code">&gt;</span>) the delegate will be called once, and the supplied delegate will call the <span class="code">RegisterAll</span> method to register a collection of the given service type. In the delegate we call the same <span class="code">RegisterAll</span> overload as was done in the first example.</p><p>With this configuration, these registrations can be resolved by calling <span class="code">container.GetInstance&lt;</span><span class="type">IEnumerable</span><span class="code">&lt;T&gt;&gt;()</span> or by calling <span class="code">container.GetAllInstances&lt;T&gt;()</span> (which is a short cut to <span class="code">GetInstance&lt;</span><span class="type">IEnumerable</span><span class="code">&lt;T&gt;&gt;()</span>). A registered collection could also be injected in a constructor that takes an <span class="type">IEnumerable</span><span class="code">&lt;T&gt;</span>, as we've seen with the <span class="type">MultipleDispatchEventHandler</span><span class="code">&lt;TEvent&gt;</span>. Constructor injection always has the preference over calling the container directly.</p><p>With this configuration in place we can now focus again on the <span class="type">MultipleDispatchEventHandler</span><span class="code">&lt;TEvent&gt;</span>. Although the earlier implementation of the <span class="type">MultipleDispatchEventHandler</span><span class="code">&lt;TEvent&gt;</span> works effectively as a composite, it doesn't handle the contravariance that we need for these event handlers. Because it is not feasible to configure the container in such way that assignable implementations are injected too, we can best solve this inside the <span class="type">MultipleDispatchEventHandler</span>'s constructor. Here's how to do it:</p><pre class="cs" language="csharp" customtypes="CustomerMovedEvent CustomerMovedAbroadEvent SpecialCustomerMovedEvent IEventHandler CustomerMovedEventHandler NotifyStaffWhenCustomerMovedEventHandler CustomerMovedAbroadEventHandler Container MultipleDispatchEventHandler" customvaluetypes="PutYourCustomValueTypesHere">public sealed class MultipleDispatchEventHandler&lt;TEvent&gt;<br />    : IEventHandler&lt;TEvent&gt;<br />{<br />    private IEnumerable&lt;IEventHandler&lt;TEvent&gt;&gt; handlers;<br /><br />    public MultipleDispatchEventHandler(Container container)<br />    {<br />        var handlersType =<br />            typeof(IEnumerable&lt;IEventHandler&lt;TEvent&gt;&gt;);<br /><br />        var handlersCollection = (<br />            from r in container.GetCurrentRegistrations()<br />            where handlersType.IsAssignableFrom(r.ServiceType)<br />            select r.GetInstance())<br />            .Cast&lt;IEnumerable&lt;IEventHandler&lt;TEvent&gt;&gt;&gt;()<br />            .ToArray();<br /><br />        this.handlers =<br />            from handlers in handlersCollection<br />            from handler in handlers<br />            select handler;<br />    }<br /><br />    void IEventHandler&lt;TEvent&gt;.Handle(TEvent e)<br />    {<br />        foreach (var handler in this.handlers)<br />        {<br />            handler.Handle(e);<br />        }<br />    }<br />}</pre><p>The code in the constructor isn't that hard to grasp, but it probably still needs some explanation. Instead of injecting an <span class="type">IEnumerable</span><span class="code">&lt;</span><span class="type">IEventHandler</span><span class="code">&lt;</span><span class="code">TEvent&gt;&gt;</span> we now inject the container itself. The <span class="type">MultipleDispatchEventHandler</span> constructor iterates over all registrations in the container and gets all registrations where <span class="type">IEnumerable</span><span class="code">&lt;</span><span class="type">IEventHandler</span><span class="code">&lt;</span><span class="code">TEvent&gt;&gt;</span> is assignable from the registration's service type. Remember that we registered the handlers using <span class="type">IEnumerable</span><span class="code">&lt;</span><span class="code">T&gt;</span>. Although the application contains three event handlers, they are contained in two <span class="type">IEnumerable</span><span class="code">&lt;</span><span class="type">IEventHandler</span><span class="code">&lt;</span><span class="code">TEvent&gt;&gt;</span> registrations.</p><p>The query results in a collection of event handler collections (a collection per registration). Calling <span class="code">ToArray()</span> on the query triggers the immediate execution of that query, which prevents the <span class="code">GetCurrentRegistrations</span> method from being called every time we iterate that collection (which will maximize performance). Leaving the elements of the array enumerables (instead of arrays) however, allows the event handlers to be lazily requested, which preserves their lifestyle (which is transient in the current configuration). This allows us to register the <span class="type">MultipleDispatchEventHandler</span> as singleton, which maximizes the performance of the application.</p><p>Note that because the <span class="type">MultipleDispatchEventHandler</span> contains registration logic, it is clearly part of the <a rel="external" href="http://blog.ploeh.dk/2011/07/28/CompositionRoot.aspx" title="Mark Seemann's blog - Composition Root">Composition Root</a>; the startup path of the application. Do not place this class inside the application, because this will force the application to have a dependency on the IoC container, which is bad practice.</p><p>The only thing missing now is the registration of the <span class="type">MultipleDispatchEventHandler </span>itself, which is a simple one-liner:</p><pre class="cs" language="csharp" customtypes="CustomerMovedEvent CustomerMovedAbroadEvent SpecialCustomerMovedEvent IEventHandler CustomerMovedEventHandler NotifyStaffWhenCustomerMovedEventHandler CustomerMovedAbroadEventHandler Container MultipleDispatchEventHandler" customvaluetypes="PutYourCustomValueTypesHere">container.RegisterSingleOpenGeneric(typeof(IEventHandler&lt;&gt;),<br />    typeof(MultipleDispatchEventHandler&lt;&gt;));</pre><p>With this in place we now have completed our first scenario.</p><h5>Scenario 2<a name="Scenario2" title="Scenario2"></a></h5><h6>Register a single implementation of a service type, and resolve a single instance.</h6><p>In this scenario we want to configure the container in such way that when we request a single event handler for a particular event, it would return the single registered instance for that event, or is case it doesn't exist, return a compatible registered event handler.</p><p style="padding-left: 30px"><em>Note: Although this scenario is perhaps a bit less likely for the example using event handlers, but it is still a realistic one, and Autofac </em><em>partially </em><em>supports this scenario out of the box. </em></p><p>Because there is a one-to-one mapping between the registered service type and the implementation, we can use the 'normal' way of registering event handlers:</p><pre class="cs" language="csharp" customtypes="CustomerMovedEvent CustomerMovedAbroadEvent SpecialCustomerMovedEvent IEventHandler CustomerMovedEventHandler NotifyStaffWhenCustomerMovedEventHandler CustomerMovedAbroadEventHandler Container MultipleDispatchEventHandler" customvaluetypes="PutYourCustomValueTypesHere">container.Register&lt;IEventHandler&lt;CustomerMovedEvent&gt;,<br />    CustomerMovedEventHandler&gt;();<br />container.Register&lt;IEventHandler&lt;CustomerMovedAbroadEvent&gt;,<br />    CustomerMovedAbroadEventHandler&gt;();</pre><p>And of course we can achieve the same using batch registration:</p><pre class="cs" language="csharp" customtypes="CustomerMovedEvent CustomerMovedAbroadEvent SpecialCustomerMovedEvent IEventHandler CustomerMovedEventHandler NotifyStaffWhenCustomerMovedEventHandler CustomerMovedAbroadEventHandler Container MultipleDispatchEventHandler" customvaluetypes="PutYourCustomValueTypesHere">container.RegisterManyForOpenGeneric(typeof(IEventHandler&lt;&gt;),<br />    typeof(IEventHandler&lt;&gt;).Assembly);<br /></pre><p>Note that the <span class="type">NotifyStaffWhenCustomerMovedEventHandler</span> is not included, since this scenario implies a single implementation per handler type, but that handler shares the same interface with the <span class="type">CustomerMovedEventHandler</span>.</p><p>With this configuration we can of course resolve an <span class="type">IEventHandler</span><span class="code">&lt;</span><span class="type">CustomerMovedEvent</span><span class="code">&gt;</span> without trouble, but resolving an <span class="type">IEventHandler</span><span class="code">&lt;</span><span class="type">SpecialCustomerMovedEvent</span><span class="code">&gt;</span>  will fail with an <span class="type">ActivationException</span>. What's missing is the resolution of unresolved types. We can do this by hooking onto the <span class="code">ResolveUnregisteredType</span> event of the <span class="type">Container</span> class, just as the <span class="code">RegisterOpenGeneric</span> and <span class="code">RegisterSingleOpenGeneric</span> extension methods of the SimpleInjector.Extensions.dll do internally.</p><p>We can for instance define a single extension method that allows mapping a missing type to an assignable type:</p><pre class="cs" language="csharp" customtypes="CustomerMovedEvent CustomerMovedAbroadEvent SpecialCustomerMovedEvent IEventHandler CustomerMovedEventHandler NotifyStaffWhenCustomerMovedEventHandler CustomerMovedAbroadEventHandler Container MultipleDispatchEventHandler" customvaluetypes="PutYourCustomValueTypesHere">public static void AllowToResolveVariantTypes(<br />    this Container container)<br />{<br />    container.ResolveUnregisteredType += (sender, e) =&gt;<br />    {<br />        Type serviceType = e.UnregisteredServiceType;<br /><br />        if (!serviceType.IsGenericType)<br />        {<br />            return;<br />        }<br /><br />        Type def = serviceType.GetGenericTypeDefinition();<br /><br />        var registrations = (<br />            from r in container.GetCurrentRegistrations()<br />            where r.ServiceType.IsGenericType<br />            where r.ServiceType.GetGenericTypeDefinition() == def<br />            where serviceType.IsAssignableFrom(r.ServiceType)<br />            select r)<br />            .ToArray();            <br />            <br />        if (!registrations.Any())<br />        {<br />            // No registration found. We're done.<br />        }<br />        else if (registrations.Length == 1)<br />        {<br />            var registration = registrations[0];<br />            e.Register(() =&gt; registration.GetInstance());<br />        }<br />        else<br />        {<br />            var names = string.Join(&quot;, &quot;, registrations<br />                .Select(r =&gt; string.Format(&quot;{0}&quot;, r.ServiceType)));<br /><br />            throw new ActivationException(string.Format(<br />                &quot;It is impossible to resolve type {0}, because &quot; +<br />                &quot;there are {1} registrations that are &quot; +<br />                &quot;applicable. Ambiguous registrations: {2}.&quot;,<br />                serviceType, registrations.Length, names));<br />        }<br />    };<br />}</pre><p>This extension method registers a delegate to the container's <span class="code">ResolveUnregisteredType</span> event. Every time an unregistered type is requested from the container, the container will first call the <span class="code">ResolveUnregisteredType</span> to get a resolution for that type, before it will try to create that type itself. The delegate is supplied with an <span class="type">UnregisteredTypeEventArgs</span> that contains a <span class="code">Register(</span><span class="type">Func</span><span class="code">&lt;</span><span class="keyword">object</span><span class="code">&gt;)</span> method, which allows the delegate to register a type. The delegate doesn't have to call the <span class="code">Register</span> method and that is what happens in this extension method. If the <span class="code">UnregisteredServiceType</span> is not generic, the delegate returns immediately, which allows other registered delegates (if any) to respond by registering a <span class="type">Func</span><span class="code">&lt;</span><span class="keyword">object</span><span class="code">&gt;</span> for that service type.</p><p>The registered delegate will query the container for assignable registrations, much like we've seen in the first scenario. When no assignable service type is found in the container, the delegate returns. Otherwise it maps the found registration to the unregistered service type (making that unregistered type effectively registered). In case there are multiple assignable registrations, an exception is thrown. In that case there is obviously some ambiguity in the registration. Of course we could try to be smarter than this, and try to resolve this ambiguity. Throwing however is the simplest thing to do :-).</p><p>What's nice about this, is that it works for both covariant (<span class="keyword">out</span>) and contravariant (<span class="keyword">in</span>) types (both for generic interfaces and generic delegates) and even for types with a mixture of in and out arguments (such as <span class="type">Func</span><span class="code">&lt;</span><span class="keyword">in</span><span class="code"> T, </span><span class="keyword">out</span><span class="code"> TResult&gt;</span>). The reason this works is because we make use of the .NET 4.0 <span class="type">Type</span><span class="code">.IsAssignableFrom</span> method, which has built-in support for variance. Compare that to Autofac for instance where support is limited to interfaces that just contain a single <span class="keyword">in</span> type argument (<span class="keyword">out</span> is not supported). Not to pick on Autofac btw, because at least Autofac has out-of-the-box support for variance, compared to most other containers.</p><p>Please note that although there is an obvious performance hit when an unregistered type is resolved this way, the penalty is one-time. The registration is cached, and although the container does not guarantee the delegate to be called just once, in normal cases it will be called just a single time. (however, you will have to make sure the delegate hooked to the <span class="code">ResolveUnregisteredType</span>  event is thread-safe, but in most cases this is a no-brainer). </p><p>With this extension method in place, we can add variance support to the container like this:</p><pre class="cs" language="csharp" customtypes="CustomerMovedEvent CustomerMovedAbroadEvent SpecialCustomerMovedEvent IEventHandler CustomerMovedEventHandler NotifyStaffWhenCustomerMovedEventHandler CustomerMovedAbroadEventHandler Container MultipleDispatchEventHandler" customvaluetypes="PutYourCustomValueTypesHere">container.AllowToResolveVariantTypes();</pre><p>With the previous registration we can now resolve the following type, even though it wasn't registered explicitly:</p><pre class="cs" language="csharp" customtypes="Assert CustomerMovedEvent CustomerMovedAbroadEvent SpecialCustomerMovedEvent IEventHandler CustomerMovedEventHandler NotifyStaffWhenCustomerMovedEventHandler CustomerMovedAbroadEventHandler Container MultipleDispatchEventHandler" customvaluetypes="PutYourCustomValueTypesHere">var handler =<br />    container.GetInstance&lt;IEventHandler&lt;SpecialCustomerMovedEvent&gt;&gt;();<br /><br />Assert.IsInstanceOfType(handler, typeof(CustomerMovedEventHandler));</pre><h5>Scenario 3<a name="Scenario3" title="Scenario3"></a></h5><h6>Register a single implementation for some service type, and resolve multiple assignable services.</h6><p>This scenario is a mix between scenario 1 and scenario 2. As with the second scenario we have just a single implementation for each service type, but want to resolve all compatible handlers for a given event, just as with scenario 1.</p><p>We can for instance register the two event handlers the same way as we did in the previous scenario:</p><pre class="cs" language="csharp" customtypes="CustomerMovedEvent CustomerMovedAbroadEvent SpecialCustomerMovedEvent IEventHandler CustomerMovedEventHandler NotifyStaffWhenCustomerMovedEventHandler CustomerMovedAbroadEventHandler Container MultipleDispatchEventHandler" customvaluetypes="PutYourCustomValueTypesHere">container.Register&lt;IEventHandler&lt;CustomerMovedEvent&gt;,<br />    CustomerMovedEventHandler&gt;();<br />container.Register&lt;IEventHandler&lt;CustomerMovedAbroadEvent&gt;,<br />    CustomerMovedAbroadEventHandler&gt;();</pre><p>When we wrap this in a composite, we get a solution that looks very much like the first scenario. The <span class="type">MultipleDispatchEventHandler</span> would look as follows:</p><pre class="cs" language="csharp" customtypes="CustomerMovedEvent CustomerMovedAbroadEvent SpecialCustomerMovedEvent IEventHandler CustomerMovedEventHandler NotifyStaffWhenCustomerMovedEventHandler CustomerMovedAbroadEventHandler Container MultipleDispatchEventHandler" customvaluetypes="PutYourCustomValueTypesHere">public sealed class MultipleDispatchEventHandler&lt;TEvent&gt;<br />    : IEventHandler&lt;TEvent&gt;<br />{<br />    private IEnumerable&lt;IEventHandler&lt;TEvent&gt;&gt; handlers;<br /><br />    public MultipleDispatchEventHandler(Container container)<br />    {<br />        var handlerType = typeof(IEventHandler&lt;TEvent&gt;);<br /><br />        var registrations = (<br />            from r in container.GetCurrentRegistrations()<br />            where handlerType.IsAssignableFrom(r.ServiceType)<br />            select r)<br />            .ToArray();<br /><br />        this.handlers =<br />            from r in registrations<br />            select (IEventHandler&lt;TEvent&gt;)r.GetInstance();<br />    }<br /><br />    void IEventHandler&lt;TEvent&gt;.Handle(TEvent e) { ... }<br />}</pre><p>However, there is a problem with this, that you will notice when trying to resolve this composite. Registering open generic types (using the <span class="code">RegisterOpenGeneric</span> or <span class="code">RegisterSingleOpenGeneric</span>) works by hooking onto the container's <span class="code">ResolveUnregisteredType</span> event, which will only get called for unregistered types. We did however already register an <span class="type">IEventHandler</span><span class="code">&lt;</span><span class="type">CustomerMovedEvent</span><span class="code">&gt;</span> and an <span class="type">IEventHandler</span><span class="code">&lt;</span><span class="type">CustomerMovedAbroadEvent</span><span class="code">&gt;</span>. Resolving those handlers will therefore result in the return of a <span class="type">CustomerMovedEventHandler</span> and <span class="type">CustomerMovedAbroadEventHandler</span> respectively. All other <span class="type">IEventHandler</span><span class="code">&lt;TEvent</span><span class="code">&gt;</span> versions will result in the return of the <span class="type">MultipleDispatchEventHandler</span>. Of course, this is not what we want.</p><p>We can fix this by registering the concrete types explicitly:</p><pre class="cs" language="csharp" customtypes="CustomerMovedEvent CustomerMovedAbroadEvent SpecialCustomerMovedEvent IEventHandler CustomerMovedEventHandler NotifyStaffWhenCustomerMovedEventHandler CustomerMovedAbroadEventHandler Container MultipleDispatchEventHandler" customvaluetypes="PutYourCustomValueTypesHere">container.Register&lt;CustomerMovedEventHandler&gt;();<br />container.Register&lt;CustomerMovedAbroadEventHandler&gt;();</pre><p>Or of course using batch registration:</p><pre class="cs" language="csharp" customtypes="CustomerMovedEvent CustomerMovedAbroadEvent SpecialCustomerMovedEvent IEventHandler CustomerMovedEventHandler NotifyStaffWhenCustomerMovedEventHandler CustomerMovedAbroadEventHandler Container MultipleDispatchEventHandler" customvaluetypes="PutYourCustomValueTypesHere">container.RegisterManyForOpenGeneric(typeof(IEventHandler&lt;&gt;),<br />    (service, impls) =&gt; container.Register(impls.Single()),<br />    AppDomain.CurrentDomain.GetAssemblies());</pre><p>The supplied registration callback in the <span class="code">RegisterManyForOpenGeneric</span> method simply calls the non-generic <span class="code">Register</span> method overload (which is new in <a rel="external" href="http://simpleinjector.codeplex.com/releases/view/68138" title="Simple Injector v1.2">v1.2</a>), and because there is only one implementation per service type, we can call <span class="code">impls.Single()</span>. In case there were more implementations, we could simply do something like this:</p><pre class="cs" language="csharp" customtypes="CustomerMovedEvent CustomerMovedAbroadEvent SpecialCustomerMovedEvent IEventHandler CustomerMovedEventHandler NotifyStaffWhenCustomerMovedEventHandler CustomerMovedAbroadEventHandler Container MultipleDispatchEventHandler" customvaluetypes="PutYourCustomValueTypesHere">container.RegisterManyForOpenGeneric(typeof(IEventHandler&lt;&gt;),<br />    (_, impls) =&gt; impls.ToList().ForEach(i =&gt; container.Register(i)),<br />    AppDomain.CurrentDomain.GetAssemblies());</pre><p>Now we have to ensure that the <span class="type">MultipleDispatchEventHandler</span> queries for these concrete types:</p><pre class="cs" language="csharp" customtypes="CustomerMovedEvent CustomerMovedAbroadEvent SpecialCustomerMovedEvent IEventHandler CustomerMovedEventHandler NotifyStaffWhenCustomerMovedEventHandler CustomerMovedAbroadEventHandler Container MultipleDispatchEventHandler" customvaluetypes="PutYourCustomValueTypesHere">public sealed class MultipleDispatchEventHandler&lt;TEvent&gt;<br />    : IEventHandler&lt;TEvent&gt;<br />{<br />    private IEnumerable&lt;IEventHandler&lt;TEvent&gt;&gt; handlers;<br /><br />    public MultipleDispatchEventHandler(Container container)<br />    {<br />        var handlerType = typeof(IEventHandler&lt;TEvent&gt;);<br /><br />        var registrations = (<br />            from r in container.GetCurrentRegistrations()<br />            let assignableInterfaces = (<br />                from intface in r.ServiceType.GetInterfaces()<br />                where handlerType.IsAssignableFrom(intface)<br />                select intface)<br />            where assignableInterfaces.Any()<br />            select r)<br />            .ToArray();<br /><br />        this.handlers =<br />            from r in registrations<br />            select (IEventHandler&lt;TEvent&gt;)r.GetInstance();<br />    }<br /><br />    void IEventHandler&lt;TEvent&gt;.Handle(TEvent e) { ... }<br />}<br /></pre><p>Instead of querying the container for <span class="type">IEventHandler</span><span class="code">&lt;TEvent</span><span class="code">&gt;</span> registrations, we query the container for service types that implement the <span class="type">IEventHandler</span><span class="code">&lt;TEvent</span><span class="code">&gt;</span> interface.</p><p>With this we successfully finished this third scenario. However, in the name of science, let's take a look at a different approach, using unregistered type resolution. Just as we did with the second scenario, we can use unregistered type resolution. Take a look at the following extension method:</p><pre class="cs" language="csharp" customtypes="IEnumerable CustomerMovedEvent CustomerMovedAbroadEvent SpecialCustomerMovedEvent IEventHandler CustomerMovedEventHandler NotifyStaffWhenCustomerMovedEventHandler CustomerMovedAbroadEventHandler Container MultipleDispatchEventHandler" customvaluetypes="PutYourCustomValueTypesHere">public static void AllowToResolveVariantCollections(<br />    this Container container)<br />{<br />    container.ResolveUnregisteredType += (sender, e) =&gt;<br />    {<br />        // Only handle IEnumerable&lt;T&gt;.<br />        if (!e.UnregisteredServiceType.IsGenericType || <br />            e.UnregisteredServiceType.GetGenericTypeDefinition() != <br />                typeof(IEnumerable&lt;&gt;))<br />        {<br />            return;<br />        }<br /><br />        Type serviceType = <br />            e.UnregisteredServiceType.GetGenericArguments()[0];<br /><br />        if (!serviceType.IsGenericType)<br />        {<br />            return;<br />        }<br /><br />        Type def = serviceType.GetGenericTypeDefinition();<br /><br />        var registrations = (<br />            from r in container.GetCurrentRegistrations()<br />            where r.ServiceType.IsGenericType<br />            where r.ServiceType.GetGenericTypeDefinition() == def<br />            where serviceType.IsAssignableFrom(r.ServiceType)<br />            select r)<br />            .ToArray();<br />        <br />        if (registrations.Any())<br />        {<br />            var instances =<br />                registrations.Select(r =&gt; r.GetInstance());<br /><br />            var castMethod = typeof(Enumerable).GetMethod(&quot;Cast&quot;)<br />                .MakeGenericMethod(serviceType);<br /><br />            var castedInstances =<br />                castMethod.Invoke(null, new[] { instances });<br /><br />            e.Register(() =&gt; castedInstances);<br />        }<br />    };<br />}</pre><p>This extension method looks much like the extension method we've seen in the second scenario, with a few differences. First of all, this extension method handles <span class="type">IEnumerable</span><span class="code">&lt;T&gt;</span> types. Just like before it searches the container for assignable types, but if they are found, an <span class="type">IEnumerable</span><span class="code">&lt;T&gt;</span> is constructed that will return all found services.</p><p>We can use this extension method as follows:</p><pre class="cs" language="csharp" customtypes="CustomerMovedEvent CustomerMovedAbroadEvent SpecialCustomerMovedEvent IEventHandler CustomerMovedEventHandler NotifyStaffWhenCustomerMovedEventHandler CustomerMovedAbroadEventHandler Container MultipleDispatchEventHandler" customvaluetypes="PutYourCustomValueTypesHere">container.AllowToResolveVariantCollections();</pre><p>With the current configuration we can now request an <span class="type">IEnumerable</span><span class="code">&lt;</span><span class="type">IEventHandler</span><span class="code">&lt;TEvent&gt;&gt;</span> and get all assignable implementations:</p><pre class="cs" language="csharp" customtypes="CustomerMovedEvent CustomerMovedAbroadEvent SpecialCustomerMovedEvent IEventHandler CustomerMovedEventHandler NotifyStaffWhenCustomerMovedEventHandler CustomerMovedAbroadEventHandler Container MultipleDispatchEventHandler" customvaluetypes="PutYourCustomValueTypesHere">var handlers = container<br />    .GetAllInstances&lt;IEventHandler&lt;CustomerMovedAbroadEvent&gt;&gt;();</pre><p>This will result in a list that contains both the <span class="type">CustomerMovedEventHandler</span> and <span class="type">CustomerMovedAbroadEventHandler</span>.</p><p>As you can see there are many ways to skin a cat. If your scenario is (slightly) different from what we've discussed and you are experiencing some difficulties in finding a good solution, please drop me a note, or <a rel="external" href="http://stackoverflow.com/questions/ask?tags=simple-injector%20ioc-container%20dependency-injection%20.net%20c%23&amp;title=Simple%20Injector:%20Contravariance" title="Ask about the Simple Injector at Stackoverflow.com">ask at Stackoverflow</a> (don't forget to tag your question with '<a rel="external" href="http://stackoverflow.com/questions/tagged/simple-injector" title="Stackoverflow - simple-injector tag">simple-injector</a>').</p><p>That's all for now.</p><h4>Happy injecting!</h4>
		]]></content>
		<author>
			<name>Steven</name>
		</author>
	</entry>
	
	
	
	<entry>
		<title>Faking your LINQ Provider part 2: Optimizing performance with fetching strategies</title>
		<link rel="alternate" type="text/html" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=89" />
		<updated>2012-01-21T11:47:00+02:00</updated>
		<published>2011-06-19T17:50:00+02:00</published>
		<id>tag:pivotpowered,2012:NETJunkie.89</id>
		<link rel="related" type="text/html" href=""  />
		<summary type="text">This sequel explains how to write O/RM specific performance optimizations in such a way that the core business logic wont be affected. This article builds on top of the foundation described in part 1 and uses the Fetching Strategy design pattern to achieve this goal.</summary>
        <content type="html" xml:lang="en" xml:base="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=89"><![CDATA[
                This sequel explains how to write O/RM specific performance optimizations in such a way that the core business logic won&rsquo;t be affected. This article builds on top of the foundation described in part 1 and uses the Fetching Strategy design pattern to achieve this goal.<p><img src="http://www.cuttingedge.it/blogs/steven/images/chain.jpg" style="float:right;margin-left:10px;margin-bottom:5px;border:1px solid" title="" alt="" class="pivot-image" />In <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=84" title=".NET Junkie's weblog - Faking your LINQ provider">part 1</a> of this series I described how to hide our LINQ enabled O/RM tool behind an abstraction with the main goal to be able to unit test the application, while keeping the ability to write LINQ (over IQueryable) queries in the business layer.</p><p>One of the short comes noted at the end of the article is that optimizing the code is harder. In fact this is only partly true, because when you have mastered the art of writing good LINQ queries, you&rsquo;ll notice that many performance problems can be fixed with it (including little neat tricks such as <a rel="external" href="http://damieng.com/" title="DamienG's blog">Damien&rsquo;s</a> <a rel="external" href="http://damieng.com/blog/2010/05/21/include-for-linq-to-sql-and-maybe-other-providers" title="DamienG - Include for LINQ to SQL (and maybe other providers)">Include extension method</a>). On the other hand, because LINQ statements tend to be written on a higher level of abstraction, our O/RM tool sometimes transforms them poorly to SQL. I had to deal with this a lot the last couple of months. Sometimes a single let statement was the <a rel="external" href="http://twitter.com/#!/dot_NET_Junkie/status/68586218958499840">difference</a> between a tunable SQL query and an hideous performance hog.</p><p>However, because we are hiding our O/RM tool behind an abstraction, it obviously gets harder to do O/RM specific optimizations. Or at least, there is no way to do this at the same place as we were used to. Think about how for instance LINQ to SQL contains the <a rel="external" href="http://msdn.microsoft.com/en-us/library/system.data.linq.dataloadoptions.aspx" title="MSDN - DataLoadOptions Class">DataLoadOptions</a> class that allows us to inform LINQ to SQL to do fetch related entities in advance. Most modern O/RM tools have similar options to configure loading behavior.</p><p>The chosen design forces us to write these optimizations in a different way, which gives us the opportunity to come with a flexible design that follows the <a rel="external" href="http://en.wikipedia.org/wiki/Solid_%28object-oriented_design%29" title="Wikipedia - SOLID">SOLID</a> design principles. For instance by applying <a rel="external" href="http://www.udidahan.com/" title="Udi Dahan's weblog">Udi Dahan&rsquo;s</a> <a rel="external" href="http://www.udidahan.com/2007/09/16/fetching-strategy-nhibernate-implementation-available/" title="Udi Dahan's weblog -    	 Fetching Strategy NHibernate Implementation Available">Fetching Strategies</a>.</p><p>The idea behind Udi&rsquo;s Fetching Strategies is to define specific classes that describe O/RM specific optimizations for a single service. The class is therefore very focused (<a rel="external" href="http://en.wikipedia.org/wiki/Single_responsibility_principle" title="Wikipedia - Single Responsibility Principle">Single Responsibility Principle</a>), and new optimizations can be plugged in easily (<a rel="external" href="http://en.wikipedia.org/wiki/Open/closed_principle" title="Wikipedia - Open-Closed Principle">Open-Closed Principle</a>), without the need to change any other part of the system. Because these optimizations are O/RM specific, you want to separate them from the services that they optimize. Those services contain the core logic of the application, working against an abstraction, while the strategies themselves are an implementation detail. These strategies could easily be located in a different assembly or even in the <a rel="external" href="http://stackoverflow.com/questions/6277771/what-is-a-composition-root-in-the-context-of-dependency-injection" title="Stackoverflow - What is a composition root in the context of Dependency Injection">composition root</a> of the application.</p><p>While the goal of the <span class="type">IUnitOfWorkFactory</span> was to hide the O/RM tool, the interface for applying optimizations does not try to hide the O/RM at all. On the contrary: the interface will be defined for a specific O/RM. For LINQ to SQL the interface might look like this:</p><pre class="cs" language="csharp" customtypes="AttributeMappingSource CommandHandlerBase Container Customer DataLoadOptions FetchingNorthwindUnitOfWorkFactory IFetchingStrategy IUnitOfWorkFactory LinqToSqlDataMapper MappingSource MoveCustomerCommand MoveCustomerCommandHandler MoveCustomerHandlerFetchingStrategy ,NorthwindUnitOfWork NorthwindUnitOfWorkFactory NullFetchingStrategy" customvaluetypes="PutYourCustomValueTypesHere">public interface IFetchingStrategy&lt;TService&gt;<br />{<br />    void Prepare(DataLoadOptions loadOptions);<br />}</pre><p>Say for instance that our system contains a <span class="type">MoveCustomerCommand</span> that gets processed by a <span class="type">MoveCustomerCommandHandler</span> (see <a rel="external" href="entry.php?id=84#application_code" title=".NET Junkie's weblog - Faking your LINQ provider - application code">an example of a command and a handler</a> in my previous article). In that case we could define a <span class="type">MoveCustomerHandlerFetchingStrategy</span> that changes the default loading behavior of the <span class="type">DataContext</span> class when the <span class="type">MoveCustomerCommandHandler</span> requests a new context:</p><pre class="cs" language="csharp" customtypes="AttributeMappingSource CommandHandlerBase Container Customer DataLoadOptions FetchingNorthwindUnitOfWorkFactory IFetchingStrategy IUnitOfWorkFactory LinqToSqlDataMapper MappingSource MoveCustomerCommand MoveCustomerCommandHandler MoveCustomerHandlerFetchingStrategy ,NorthwindUnitOfWork NorthwindUnitOfWorkFactory NullFetchingStrategy" customvaluetypes="PutYourCustomValueTypesHere">public sealed class MoveCustomerHandlerFetchingStrategy<br />    : IFetchingStrategy&lt;MoveCustomerCommandHandler&gt;<br />{<br />    public void Prepare(DataLoadOptions loadOptions)<br />    {<br />        loadOptions.LoadWith&lt;Customer&gt;(c =&gt; c.Orders);<br />    }<br />}</pre><p>This fetching strategy just tells the LINQ to SQL <span class="type">DataLoadOptions</span> instance that for each customer that it loads from the database, it should load all its orders in the same SQL query.</p><p>It might seem that this approach gives a lot of overhead, but don&rsquo;t forget that we would probably just end up with a dozen of fetching strategy classes, because we would only add a new strategy when we&rsquo;ve got a performance problem.</p><p>Defining the interface and a concrete strategy is the easy part. Now we must ensure that fetching strategies get applied on the service they relate to. There are several ways to do this. A na&iuml;ve approach would be to inject a fetching strategy directly into the particular service. This will unfortunately break the abstraction. Here is an example:</p><pre class="cs badcode" language="csharp" customtypes="NorthwindUnitOfWork AttributeMappingSource CommandHandlerBase Container Customer DataLoadOptions FetchingNorthwindUnitOfWorkFactory IFetchingStrategy IUnitOfWorkFactory LinqToSqlDataMapper MappingSource MoveCustomerCommand MoveCustomerCommandHandler MoveCustomerHandlerFetchingStrategy ,NorthwindUnitOfWork NorthwindUnitOfWorkFactory NullFetchingStrategy ICommandHandler" customvaluetypes="PutYourCustomValueTypesHere">public class MoveCustomerCommandHandler<br />    : ICommandHandler&lt;MoveCustomerCommand&gt;<br />{<br />    private IFetchingStrategy&lt;MoveCustomerCommandHandler&gt; strategy;<br />    private IUnitOfWorkFactory&lt;NorthwindUnitOfWork&gt; factory;<br /><br />    public MoveCustomerCommandHandler(<br />        IFetchingStrategy&lt;MoveCustomerCommandHandler&gt; strategy,<br />        IUnitOfWorkFactory&lt;NorthwindUnitOfWork&gt; factory)<br />    {<br />        this.strategy = strategy;<br />        this.factory = factory;<br />    }<br /><br />    public void Handle(MoveCustomerCommand command)<br />    {<br />        using (var context = this.factory.CreateNew())<br />        {<br />            var options = new System.Data.Linq.DataLoadOptions();<br /><br />            this.strategy.Prepare(options);<br /><br />            // Set the options to the L2S DataContext here.<br /><br />            // Business logic<br />        }<br />    }<br />}</pre><p>There are a few problems with this approach. First of all, this is still too much code for something that should work transparently in the background. Besides this (or perhaps even because of this) it is easy to forget about preparing the context with a fetching strategy and in that case, we would end up having to change the class to add this when we need the performance optimization. This would therefore break with the Open-Closed principle. But more importantly, this couples our business logic to a specific O/RM framework (LINQ to SQL in this case), which was the thing that we tried to prevent in the first place. In other words, this is not the way to go.</p><p>It would be better to let the unit of work factory handle preparing the context itself. It is the specific unit of work factory implementation that knows about the used O/RM technology and has a reference to the <span class="type">DataContext</span> class. The question now becomes: how do we let the factory know how it should prepare the <span class="type">DataContext</span>?</p><p>The easiest way to do this, would be to pass the type of our current service on to the factory. This can be done as follows:</p><pre class="cs" language="csharp" customtypes="NorthwindUnitOfWork AttributeMappingSource CommandHandlerBase Container Customer DataLoadOptions FetchingNorthwindUnitOfWorkFactory IFetchingStrategy IUnitOfWorkFactory LinqToSqlDataMapper MappingSource MoveCustomerCommand MoveCustomerCommandHandler MoveCustomerHandlerFetchingStrategy ,NorthwindUnitOfWork NorthwindUnitOfWorkFactory NullFetchingStrategy" customvaluetypes="PutYourCustomValueTypesHere">    public MoveCustomerCommandHandler(<br />        IUnitOfWorkFactory&lt;NorthwindUnitOfWork&gt; factory)<br />    {<br />        this.factory = factory;<br />    }<br /><br />    public void Handle(MoveCustomerCommand command)<br />    {<br />        // Here we pass the &lsquo;this&rsquo; argument to the CreateNew.<br />        using (var context = this.factory.CreateNew(this))<br />        {<br />             // Business logic<br />        }<br />    }</pre><p>For this to work we need to change the definition of the <span class="type">IUnitOfWorkFactory</span><span class="code">&lt;TUnitOfWork&gt;</span> interface to the following:</p><pre class="cs" language="csharp" customtypes="AttributeMappingSource CommandHandlerBase Container Customer DataLoadOptions FetchingNorthwindUnitOfWorkFactory IFetchingStrategy IUnitOfWorkFactory LinqToSqlDataMapper MappingSource MoveCustomerCommand MoveCustomerCommandHandler MoveCustomerHandlerFetchingStrategy ,NorthwindUnitOfWork NorthwindUnitOfWorkFactory NullFetchingStrategy" customvaluetypes="PutYourCustomValueTypesHere">public interface IUnitOfWorkFactory&lt;TUnitOfWork&gt;<br />{<br />    TUnitOfWork CreateNew&lt;TService&gt;(TService service);<br />}</pre><p>A particular implementation could then look like this:</p><pre class="cs" language="csharp" customtypes="AttributeMappingSource CommandHandlerBase Container Customer DataLoadOptions FetchingNorthwindUnitOfWorkFactory IFetchingStrategy IUnitOfWorkFactory LinqToSqlDataMapper MappingSource MoveCustomerCommand MoveCustomerCommandHandler MoveCustomerHandlerFetchingStrategy ,NorthwindUnitOfWork NorthwindUnitOfWorkFactory NullFetchingStrategy NorthwindUnitOfWork DataContext" customvaluetypes="PutYourCustomValueTypesHere">// This is a LINQ to SQL specific implementation.<br />public sealed class NorthwindUnitOfWorkFactory<br />    : IUnitOfWorkFactory&lt;NorthwindUnitOfWork&gt;<br />{<br />    private static MappingSource Source = <br />        new AttributeMappingSource();<br /><br />    // A reference to the application&rsquo;s DI container.<br />    private readonly Container container;<br />    private readonly string conStr;<br /><br />    public NorthwindUnitOfWorkFactory(Container container, <br />        string conStr)<br />    {<br />        this.container = container;<br />        this.conStr = conStr;<br />    }<br /><br />    public NorthwindUnitOfWork CreateNew&lt;TService&gt;(TService service)<br />    {<br />        var db = new DataContext(this.conStr, Source);<br /><br />        this.Prepare&lt;TService&gt;(db);<br /><br />        var mapper = new LinqToSqlDataMapper(db);<br /><br />        return new NorthwindUnitOfWork(mapper);<br />    }<br /><br />    private void Prepare&lt;TService&gt;(DataContext db)<br />    {<br />        // Get a strategy for the correct type from the container.<br />        var fetchingStrategy = <br />            this.container.GetInstance&lt;IFetchingStrategy&lt;TService&gt;&gt;();<br /><br />        var loadOptions = new DataLoadOptions();<br /><br />        fetchingStrategy.Prepare(loadOptions);<br /><br />        // Register the load options to the DataContext.<br />        db.LoadOptions = loadOptions;<br />    }<br />}</pre><p>Nice about this approach is that it is pretty easy to implement and easy to grasp. Downside is that there is now some sort of wart in our code, that instantly seems less clean. Why should we pass on the service itself onto the factory? I rather inject a factory into the service that already knows how to do the proper preparation. For this to work however, we need context based injection.</p><p>Context based dependency injection is the ability to base the decision about what to inject on the context in which the dependency is injected. In our case it would be useful to make the decision based on the type the dependency is injected in. In other words, we base the actual factory type on the type of the service in which we inject that factory. Defining a generic factory allows us to specify the service type we need:</p><pre class="cs" language="csharp" customtypes="NorthwindUnitOfWork IDataMapper AttributeMappingSource CommandHandlerBase Container Customer DataLoadOptions FetchingNorthwindUnitOfWorkFactory IFetchingStrategy IUnitOfWorkFactory LinqToSqlDataMapper MappingSource MoveCustomerCommand MoveCustomerCommandHandler MoveCustomerHandlerFetchingStrategy ,NorthwindUnitOfWork NorthwindUnitOfWorkFactory NullFetchingStrategy" customvaluetypes="PutYourCustomValueTypesHere">public sealed class FetchingNorthwindUnitOfWorkFactory&lt;TService&gt;<br />    : IUnitOfWorkFactory&lt;NorthwindUnitOfWork&gt;<br />{<br />    private IFetchingStrategy&lt;TService&gt; fetchingStrategy;<br />    private IUnitOfWorkFactory&lt;NorthwindUnitOfWork&gt; realFactory;<br /><br />    public FetchingNorthwindUnitOfWorkFactory(<br />        IFetchingStrategy&lt;TService&gt; fetchingStrategy,<br />        IUnitOfWorkFactory&lt;NorthwindUnitOfWork&gt; realFactory)<br />    {<br />        this.fetchingStrategy = fetchingStrategy;<br />        this.realFactory = realFactory;<br />    }<br /><br />    public NorthwindUnitOfWork CreateNew()<br />    {<br />        var unitOfWork = this.realFactory.CreateNew();<br /><br />        this.Prepare(unitOfWork.Mapper);<br /><br />        return unitOfWork;<br />    }<br /><br />    private void Prepare(IDataMapper mapper)<br />    {<br />        var loadOptions = new DataLoadOptions();<br /><br />        this.fetchingStrategy.Prepare(loadOptions);<br /><br />        var dataMapper = (LinqToSqlDataMapper)mapper;<br /><br />        dataMapper.Context.LoadOptions = loadOptions;<br />    }<br />}</pre><p>This factory is a generic type and depends on an <span class="type">IFetchingStrategy</span><span class="code">&lt;TService&gt;</span> where the generic type of that strategy is the same as that of the factory. By requesting a factory from the DI container for a specific service, it would be loaded with the fetching strategy that is specific for the given service.</p><p>Also note how this factory wraps another factory; the factory that actually creates the context (see part 1 for the code for that factory). Besides adhering to the Open-Closed Pinciple (OCP), this allows us to inject the &lsquo;normal&rsquo; factory for groups of types that never have any strategy defined for them, while injecting this factory for groups of types that do. Also note how the factory itself is clean of the container itself, which makes it easier to test it.</p><p><em>Warning: I&rsquo;m trying to keep things simple. Although the previous class adherers to the OCP, it breaks the <a rel="external" href="http://en.wikipedia.org/wiki/Liskov_substitution_principle" title="Wikipedia - Liskov substitution principle">Liskov Substitution Principle</a>.</em></p><p>Now we need context based injection to inject the correct instance into a service that depends on an <span class="type">IUnitOfWorkFactory</span><span class="code">&lt;</span><span class="type">NorthwindUnitOfWork</span><span class="code">&gt;</span>. Context based injection however, is an advanced feature that not all DI containers natively support. Containers such as <a rel="external" href="http://code.google.com/p/autofac/" title="Autofac">Autofac</a> and my own <a rel="external" href="http://simpleinjector.codeplex.com" title="Simple Injector">Simple Injector</a>, lack this feature. This doesn&rsquo;t mean however that it is impossible to do such things with these containers. On the contrary; The way to achieve this is by breaking the dependency chain and moving from constructor injection to property injection and moving that property to a non-generic base class. Downside of this is that it forces us to add a base class, but on the plus side it keeps our registration fairly clean and works with most DI containers (and is therefore a good example for this blog post).</p><p>We can for instance define a non-generic base class that all command handlers should inherit from.</p><pre class="cs" language="csharp" customtypes="NorthwindUnitOfWork AttributeMappingSource CommandHandlerBase Container Customer DataLoadOptions FetchingNorthwindUnitOfWorkFactory IFetchingStrategy IUnitOfWorkFactory LinqToSqlDataMapper MappingSource MoveCustomerCommand MoveCustomerCommandHandler MoveCustomerHandlerFetchingStrategy ,NorthwindUnitOfWork NorthwindUnitOfWorkFactory NullFetchingStrategy" customvaluetypes="PutYourCustomValueTypesHere">public abstract class CommandHandlerBase<br />{<br />    public IUnitOfWorkFactory&lt;NorthwindUnitOfWork&gt; Factory { get; set; }<br />}</pre><p>The <span class="type">MoveCustomerCommandHandler</span> that we&rsquo;ve seen earlier will now have to inherit from <span class="type">CommandHandlerBase</span>:</p><pre class="cs" language="csharp" customtypes="ICommandHandler AttributeMappingSource CommandHandlerBase Container Customer DataLoadOptions FetchingNorthwindUnitOfWorkFactory IFetchingStrategy IUnitOfWorkFactory LinqToSqlDataMapper MappingSource MoveCustomerCommand MoveCustomerCommandHandler MoveCustomerHandlerFetchingStrategy ,NorthwindUnitOfWork NorthwindUnitOfWorkFactory NullFetchingStrategy" customvaluetypes="PutYourCustomValueTypesHere">public class MoveCustomerCommandHandler : CommandHandlerBase,<br />    ICommandHandler&lt;MoveCustomerCommand&gt;<br />{<br />    public void Handle(MoveCustomerCommand command)<br />    {<br />        using (var context = this.Factory.CreateNew())<br />        {<br />            // Business logic<br />        }<br />    }<br />}</pre><p>What&rsquo;s left is the registration of the DI container. Here is an example of how to do this with the Simple Injector:</p><pre class="cs" language="csharp" customtypes="AttributeMappingSource CommandHandlerBase Container Customer DataLoadOptions FetchingNorthwindUnitOfWorkFactory IFetchingStrategy IUnitOfWorkFactory LinqToSqlDataMapper MappingSource MoveCustomerCommand MoveCustomerCommandHandler MoveCustomerHandlerFetchingStrategy ,NorthwindUnitOfWork NorthwindUnitOfWorkFactory NullFetchingStrategy NorthwindUnitOfWork" customvaluetypes="PutYourCustomValueTypesHere">container.RegisterInitializer&lt;CommandHandlerBase&gt;(handler =&gt;<br />{<br />    var type = typeof(FetchingNorthwindUnitOfWorkFactory&lt;&gt;)<br />        .MakeGenericType(handler.GetType());<br /><br />    handler.Factory = (IUnitOfWorkFactory&lt;NorthwindUnitOfWork&gt;)<br />        container.GetInstance(type);<br />});</pre><p>This code registers an event that will be called every time an instance that derives from <span class="type">CommandHandlerBase</span> is created by the container. Based on the actual type of that instance, we determine the type of the <span class="type">FetchingNorthwindUnitOfWorkFactory</span><span class="code">&lt;T&gt;</span>, request that from the container, and inject it into the property of the base type.</p><p>This type of registration works with almost all modern DI containers. As far as I see, the only container that does not support this is <a rel="external" href="http://unity.codeplex.com/" title="Unity">Microsoft Unity</a>. The only way I can think of to solve this with Unity is by calling a static instance of the container from within the <span class="type">CommandHandlerBase</span> class; yuck! If anyone knows a better way, please let me know. I will update the article.</p><p>The <a rel="external" href="http://simpleinjector.codeplex.com/" title="Simple Injector">Simple Injector</a> however, does contain some interesting extension points that allow to add features such as context based injection. The <a rel="external" href="http://simpleinjector.codeplex.com/documentation" title="Simple Injector - Documentation">Simple Injector documentation </a>contains <a rel="external" href="simpleinjector.codeplex.com/wikipage?title=Advanced-scenarios#Context_Based_Injection" title="Simple Injector - Advanced Scenarios - Context Based Injection">a section about context based injection</a> and describes a <a rel="external" href="http://simpleinjector.codeplex.com/wikipage?title=ContextDependentExtensions" title="Simple Injector - Adding context dependent injection to the Simple Injector">RegisterWithContext extension method</a>. When using this method you can remove the <span class="type">CommandHandlerBase</span> class and return to injecting a <span class="type">IUnitOfWorkFactory</span><span class="code">&lt;</span><span class="type">NorthwindUnitOfWork</span><span class="code">&gt;</span> into the constructor of your services. Instead of registering an initializer for the <span class="type">CommandHandlerBase</span>, we can simply register the <span class="type">IUnitOfWorkFactory</span><span class="code">&lt;</span><span class="type">NorthwindUnitOfWork</span><span class="code">&gt;</span> using the <span class="code">RegisterWithContext</span> extension method:</p><pre class="cs" language="csharp" customtypes="IUnitOfWorkFactory NorthwindUnitOfWork FetchingNorthwindUnitOfWorkFactory" customvaluetypes="PutYourCustomValueTypesHere">container.RegisterWithContext&lt;IUnitOfWorkFactory&lt;NorthwindUnitOfWork&gt;&gt;(<br />    context =&gt;<br />    {<br />        var type = typeof(FetchingNorthwindUnitOfWorkFactory&lt;&gt;)<br />            .MakeGenericType(context.ImplementationType);<br /><br />        return (IUnitOfWorkFactory&lt;NorthwindUnitOfWork&gt;)<br />            container.GetInstance(type);<br />    });</pre><p>The code looks much like the previous <span class="code">RegisterInitializer</span> registration, but now uses the supplied <span class="code">context</span> to get the <span class="code">ImplementationType</span>.</p><p><em>Please note that this code is specific to the Simple Injector, and it might be difficult to translate it to another container. </em></p><p>The <span class="type">FetchingNorthwindUnitOfWorkFactory</span><span class="code">&lt;T&gt;</span> class depends on a <span class="type">IFetchingStrategy</span><span class="code">&lt;TService&gt;</span>, so of course we must also register the fetching strategies:</p><pre class="cs" language="csharp" customtypes="IFetchingStrategy" customvaluetypes="PutYourCustomValueTypesHere">container.RegisterManyForOpenGeneric(typeof(IFetchingStrategy&lt;&gt;),<br />    AppDomain.CurrentDomain.GetAssemblies());</pre><p>This searches through all assemblies in the current AppDomain looking for concrete types that implement a closed generic version of the <span class="type">IFetchingStrategy</span><span class="code">&lt;TService&gt;</span> interface and registers them by that interface. This type of registration is called batch registration. Because however, most services will not have any fetching strategy class defined for them, we must register a fallback implementation for those:</p><pre class="cs" language="csharp" customtypes="IFetchingStrategy NullFetchingStrategy" customvaluetypes="PutYourCustomValueTypesHere">container.RegisterOpenGeneric(typeof(IFetchingStrategy&lt;&gt;), <br />    typeof(NullFetchingStrategy&lt;&gt;));</pre><p>The <span class="type">NullFetchingStrategy</span><span class="code">&lt;TService&gt;</span> is an implementation of the <a rel="external" href="http://en.wikipedia.org/wiki/Null_Object_pattern" title="Wikipedia - Null Object pattern">Null Object Pattern</a>, which is of course trivial. I won&rsquo;t bore you with that. This registration will return a new instance of <span class="type">NullFetchingStrategy</span><span class="code">&lt;TService&gt;</span> when a <span class="type">IFetchingStrategy</span><span class="code">&lt;TService&gt;</span> is requested. Note that the batch registrations done with <span class="code">RegisterManyForOpenGeneric</span> will always preceed these registrations.</p><p>If you are interested in applying this idea in your application, but don&rsquo;t know how to do this with the DI container you currently use in your application; take a look at the <a rel="external" href="http://simpleinjector.codeplex.com/wikipage?title=Migration%20Guide&amp;referringTitle=Documentation" title="Simple Injector - Migration Guide">Simple Injector migration guide</a>. It shows you how to rewrite all the above registration snippets in the container of your choice.</p><h5>Short comes</h5><p>While part one of this series described a model that allowed to work with multiple data sources and even multiple O/RM technologies side-by-side, I left that out of this part. Adding that wouldn&rsquo;t be that difficult, though.</p><p>One thing to note is that it gets much harder to use fetching strategies when you execute multiple commands within the same unit of work, for instance when a command has multiple sub commands. There are two solutions I can think of. Either we apply solely the fetching strategy for the main command to the DataContext (the easiest thing to do), or we apply all strategies to the context before the command is executes. </p><h5>Conclusion</h5><p>Fetching strategies are a valuable pattern that allow you to fix O/RM specific performance problems without coupling your main application logic to the chosen O/RM technology.</p><p>Happy injecting!</p>
		]]></content>
		<author>
			<name>Steven</name>
		</author>
	</entry>
	
	
	
	<entry>
		<title>Simple Injector: Working with multiple constructors</title>
		<link rel="alternate" type="text/html" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=88" />
		<updated>2011-12-17T18:38:00+02:00</updated>
		<published>2011-05-28T13:30:00+02:00</published>
		<id>tag:pivotpowered,2012:NETJunkie.88</id>
		<link rel="related" type="text/html" href=""  />
		<summary type="text">Although limited in features, the Simple Injector has simple but flexible way to add features, such as the possibility to work with multiple constructors.</summary>
        <content type="html" xml:lang="en" xml:base="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=88"><![CDATA[
                Although limited in features, the Simple Injector has simple but flexible way to add features, such as the possibility to work with multiple constructors.<p><img src="http://www.cuttingedge.it/blogs/steven/images/nurse1.jpg" style="float:right;margin-left:10px;margin-bottom:5px;border:1px solid" title="" alt="" class="pivot-image" />I read <a rel="external" href="http://www.planetgeek.ch/author/remo-gloor/" title="Remo Gloor's weblog">Remo Gloor's weblog</a> today. <a rel="external" href="http://stackoverflow.com/users/448580/remo-gloor" title="Stackoverflow - Remo Gloor">Remo Gloor</a> is a developer on <a rel="external" href="http://ninject.org/">Ninject</a>. In <a rel="external" href="http://www.planetgeek.ch/2011/05/28/ninject-constructor-selection-preview/" title="Ninject constructor selection preview">his latest blog post</a>, he describes a new feature of the coming Ninject release concerning constructor selection. The Ninject team is going to add a new feature that allows developers to configure which constructor overload Ninject should pick to create that type.</p><p>I'm not a fan of such a feature, because this steers developers away from a clean application design. Types that act as service components, should contain a single definition of the required dependencies. Since constructor injection is the primary way to inject our dependencies, it doesn't make much sense to have multiple (public) constructors, because we end up with multiple definitions of what dependencies a class requires.</p><p>The problem with adding features that support corner case scenario&rsquo;s is that they tend to pollute the framework&rsquo;s API. While existing users won't notice the slowly increasing API surface (just like frogs tend to stay in the water when it is heated slowly), new users get overwhelmed. Because of this I try to keep the feature set of <a rel="external" href="http://simpleinjector.codeplex.com" title="Simple Injector">Simple Injector</a> minimal. Even the feature set of the SimpleInjector.Extensions library is fairly limited.</p><p>Funny thing however, is that such a feature, as Remo is adding in the next Ninject version, is already very easy to implement with the Simple Injector, simply by adding an extension method. Here is an example:</p><p><font color="#FF0000">Update [2011-12-13]: This code was updated for the Simple Injector v1.3 release.</font></p><pre class="cs" language="csharp" customtypes="IConstructorSelector Container Expression Func NewExpression" customvaluetypes="PutYourCustomValueTypesHere">public static void Register&lt;TService, TImplementation&gt;(<br />    this Container container, IConstructorSelector selector)<br />    where TService : class<br />{<br />    container.Register&lt;TService&gt;(() =&gt; null);<br /><br />    container.ExpressionBuilt += (sender, e) =&gt;<br />    {<br />        if (e.RegisteredServiceType == typeof(TService))<br />        {<br />            var ctor =<br />                selector.GetConstructor(typeof(TImplementation));<br /><br />            var parameters =<br />                from p in ctor.GetParameters()<br />                select container.GetRegistration(p.ParameterType, true)<br />                    .BuildExpression();<br /><br />            e.Expression = Expression.New(ctor, parameters);<br />        }<br />    };<br />}</pre><p>This extension method does two things. First it registers the service with a 'fake' delegate. This ensures that nobody can exidentally override the implementation, and it ensures the <span class="code">ExpressionBuilt</span> event will get triggered (since it only gets triggered for registered types). Next it hooks a delegate to the <span class="code">ExpressionBuilt</span> event. The <span class="code">ExpressionBuilt</span> event will get raised every time the container builds an <span class="type">Expression</span> object for the creation of a service type, but before this Expression gets compiled to a <span class="type">Func</span><span class="code">&lt;T&gt;</span> delegate. This allows us to influence how the container creates a type, which is exactly what we're doing here. When the delegate gets called, we first check whether the event gets raised for our <span class="code">TService</span> (otherwise we skip), and if so, we fetch the constructor we wish to use using the supplied <span class="type">IConstructorSelector</span> instance (shown below). Using this constructor we create a <span class="type">NewExpression</span> instance that allows us to create a new instance of the given <span class="code">TImplementation</span> using retrieved constructor, by supplying it the correct set of parameters. </p><p>Here is the <span class="type">IConstructorSelector</span> interface with with a convenient default implementation:</p><pre class="cs" language="csharp" customtypes="IConstructorSelector ConstructorInfo ConstructorSelector" customvaluetypes="PutYourCustomValueTypesHere">public interface IConstructorSelector<br />{<br />    ConstructorInfo GetConstructor(Type type);<br />}<br /><br />public sealed class ConstructorSelector : IConstructorSelector<br />{<br />    public static readonly IConstructorSelector MostParameters =<br />        new ConstructorSelector(type =&gt; type.GetConstructors()<br />            .OrderByDescending(c =&gt; c.GetParameters().Length).First());<br /><br />    public static readonly IConstructorSelector LeastParameters =<br />        new ConstructorSelector(type =&gt; type.GetConstructors()<br />            .OrderBy(c =&gt; c.GetParameters().Length).First());<br /><br />    private readonly Func&lt;Type, ConstructorInfo&gt; selector;<br /><br />    public ConstructorSelector(Func&lt;Type, ConstructorInfo&gt; selector)<br />    {<br />        this.selector = selector;<br />    }<br /><br />    public ConstructorInfo GetConstructor(Type type)<br />    {<br />        return this.selector(type);<br />    }<br />}</pre><p>With this in place, we can simply register a multi constructor type as follows:</p><pre class="cs" language="csharp" customtypes="IService MyServiceImpl ILogger IRepository ConstructorSelector" customvaluetypes="PutYourCustomValueTypesHere">container.Register&lt;IService, MyServiceImpl&gt;(<br />    ConstructorSelector.MostParameters);</pre><p>Because we use <span class="type">Expression</span> objects here, retrieving instances like this pure fire, just as it is with the normal <span class="code">Register&lt;TService, TImplementation&gt;()</span> method.</p><p>I like to repeat that I discourage anyone to specify multiple constructors on a type, so the usefulness of this feature is limited. Nevertheless did it give me the possibility to showcase the extendibility of the Simple Injector :-).</p><h4>Happy injecting.</h4>
		]]></content>
		<author>
			<name>Steven</name>
		</author>
	</entry>
	
	
	
	<entry>
		<title>Simple Injector - The easiest Dependency Injection framework in town</title>
		<link rel="alternate" type="text/html" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=87" />
		<updated>2012-01-01T15:32:00+02:00</updated>
		<published>2011-05-01T18:15:00+02:00</published>
		<id>tag:pivotpowered,2012:NETJunkie.87</id>
		<link rel="related" type="text/html" href=""  />
		<summary type="text">The Simple Injector is an easy-to-use Inversion of Control library for  .NET and Silverlight. It solely supports code-based configuration and is  an ideal starting point for developers unfamiliar with larger IoC / DI  libraries.</summary>
        <content type="html" xml:lang="en" xml:base="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=87"><![CDATA[
                The Simple Injector is an easy-to-use Inversion of Control library for  .NET and Silverlight. It solely supports code-based configuration and is  an ideal starting point for developers unfamiliar with larger IoC / DI  libraries.<p style="border: 2px solid #00cc00; padding: 4px; background-color: #eeffee"><strong>Download:</strong> The Simple Injector library and source code can be downloaded from <a rel="external external external" href="http://codeplex.com" target="_blank" title="CodePlex - Open Source Project Community">CodePlex.com</a>. Visit the homepage at <a rel="external external external" href="http://simpleinjector.codeplex.com" target="_blank" title="Simple Injector - truly simple dependency injection">simpleinjector.codeplex.com</a> or go directly to the <a rel="external external external" href="http://simpleinjector.codeplex.com/releases/" target="_blank" title="Simple Injector - Downloads">Downloads</a> tab.</p>  <p><img src="http://www.cuttingedge.it/blogs/steven/images/di.jpg" style="float:right;margin-left:10px;margin-bottom:5px;border:1px solid" title="Dependency Injection" alt="Dependency Injection" class="pivot-image" />Readers that are already familiar with the <em>Simple Service Locator</em> might be wondering what happened with it. Nothing has happened with it. I released <a rel="external" href="http://simpleinjector.codeplex.com/releases/view/56439" title="Simple Service Locator v1.0">a stable release</a> over a month ago and you can still download it.</p><p>The <strong><em>Simple Injector</em></strong> is a fork of the code base of the <em>Simple Service Locator</em> and shared almost the exact same API as the <em>Simple Service Locator</em>. There is a reason however, why I renamed the <em>Simple Service Locator</em>.</p><p>In earlier posts (<a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=85" title="Do we need the Common Service Locator?">here</a> and <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=86" title="Removing Keyed Registrations from the Simple Service Locator">here</a>) on my blog, I question the usefulness of the <a rel="external" href="http://commonservicelocator.codeplex.com/" title="Common Service Locator">Common Service Locator</a> and keyed registrations. I decided that I didn&rsquo;t want to remove those features from the Simple Service Locator, because it could annoy existing users. I had however, strong reasons to remove those, because I didn&rsquo;t feel those features did belong there.</p><p>Because I wanted to introduce some major breaking changes, such as removing the hard dependency on the <em>Common Service Locator</em> and the removal of keyed registrations, I decided to change the name of the new version. This has a few advantages. First of all, this communicates clearly that this is not the <em>Simple Service Locator</em> and users should not expect it to be compatible. Besides this, the name of the <em>Simple Service Locator</em> was chosen, because it is an implementation of the <em>Common Service Locator</em>. Since I removed the dependency with the <em>Common Service Locator</em>, there was no reason to call the library &lsquo;Simple Service Locator&rsquo;, which was a controversial name in the first place. It lead to a lot of confusion.</p><p>Because of the above, I &lsquo;rebranded&rsquo; the library, which is now called &rdquo;Simple Injector&rdquo;. I will still maintain the <em>Simple Service Locator</em>, but the focus of development and documentation lies with the <em>Simple Injector</em>. You can see the <em>Simple Service Locator</em> as feature complete. It&rsquo;s done, just like LINQ to SQL is &lsquo;done&rsquo; :-).</p><h5>So what are the differences with the Simple Service Locator anyway?</h5><h6>1. No more Common Service Locator <br /></h6><p>Like I said, I removed the dependency on the <em>Common Service Locator</em> (CSL). This means that you don&rsquo;t need the Microsoft.Practices.ServiceLocation.dll anymore. If you still want to hide the <em>Simple Injector</em> behind the CSL fa&ccedil;ade, you still can. There is now an CSL Adapter available in the download.</p><h6>2. No more keyed registrations <br /></h6><p>Second difference is the removal of the keyed registrations. Keyed registrations make sense in two situations. It makes sense when you are calling into the container itself directly from within your application, and second, it makes sense when using keyed registrations for registration purposes. Some DI containers contain many examples in their documentation were keyed registrations are used for things as decorators or collections of instances.</p><p>The thing is however, that calling into the container itself is a pattern known as the <a rel="external" href="http://en.wikipedia.org/wiki/Service_locator_pattern" title="Service Locator pattern">Service Locator pattern</a>, and is typically considered an <a rel="external" href="http://blog.ploeh.dk/2010/02/03/ServiceLocatorIsAnAntiPattern.aspx" title="Mark Seemann's .NET blog - Service Locator is an Anti-Pattern">anti-pattern</a>. I agree with this and it is the main reason for me changing the library so drastically.</p><p>The containers that use keyed registrations as examples are mostly the containers that do not allow concrete unregistered types to be resolved (such as Autofac and Castle Windsor). <em>Simple Injector</em> (or <em>Simple Service Locator</em> for that matter) allow unregistered concrete types to be resolved (just as Unity and StructureMap do). The reason for those other frameworks not to do this by default, is because it is considered bad practice to depend on concrete implementations. I agree with that, but this doesn&rsquo;t mean you shouldn&rsquo;t be able to resolve a concrete type if you want to. In fact, allowing concrete instances to be resolved, it makes the actual DI configuration much simpler, and that&rsquo;s really what the <em>Simple Injector</em> is all about. I haven&rsquo;t found a scenario yet that could only be solved by using keyed / named registrations with the <em>Simple Injector</em>. Because of all this, I simply had to remove it from the library. If you really want to be able to resolve an instance by a key though, just create an abstract factory. <a rel="external" href="http://simpleinjector.codeplex.com/wikipage?title=Advanced-scenarios#Resolving_Instances_By_Key" title="Simple Injector wiki - Advanced scenarios - Resolving Instances By Key">It&rsquo;s so simple to do so</a>, that this by itself justifies not having such a feature in the library.</p><h6>3. Silverlight <br /></h6><p>Besides these two changes, there are other changes, such as Silverlight support. While <em>Simple Service Locator</em> always intended to have Silverlight support, it didn&rsquo;t really work. I pulled the support from the stable release of the <em>Simple Service Locator.</em> To get this to work in the Silverlight sandbox, was actually quite a lot of work. <em>Simple Injector</em> now supports Silverlight (and the solution now has a full set of unit tests for Silverlight, that will ensure that it will keep working).</p><h6>4. Extensions for more advanced stuff <br /></h6><p><em>Simple Injector</em> now contains an <em>Extensions</em> assembly, that can be added when you want advanced features. The project existed in the <em>Simple Service Locator</em> source code, but it just contained a bunch of example code snippets. For <em>Simple Injector</em>, that project is now fully tested and part of the download. Placing this stuff in a separate assembly, allows the core to be really slim and easy to grasp.</p><h6>5. Good support for property injection <br /></h6><p>The <em>Simple Service Locator</em> contains <span class="code">Register&lt;TConcrete&gt;(</span><span class="type">Action</span><span class="code">&lt;TConcrete&gt;)</span> and <span class="code">RegisterSingle&lt;TConcrete&gt;(</span><span class="type">Action</span><span class="code">&lt;TConcrete&gt;)</span> overloads that allow registering a concrete type and hook up an <span class="type">Action</span><span class="code">&lt;T&gt;</span> delegate that allow initializing that type after it is created. Unfortunately, this only works with concrete types. In the <em>Simple Injector</em> project these methods are replaced with a single <span class="code">RegisterInitializer&lt;T&gt;(</span><span class="type">Action</span><span class="code">&lt;T&gt;)</span> method. This method allows registration of delegates for each and every type. For instance, when you hook up an <span class="type">Action</span><span class="code">&lt;</span><span class="keyword">object</span><span class="code">&gt;</span> delegate, it will be called for each and every instance created by the container. While this might not be that useful, it shows the power of this feature. The main scenario for this feature is property injection. The feature allows to register a delegate for a base type, and it will run after the creation of every type that derives from it (or implements it, if it's an interface). There is one catch though, with this feature. While this feature has a one-to-one mapping for some DI frameworks (such as Autofac), you can have a hard time doing this with others (such as Castle Windsor and Unity). I am writing a <a rel="external" href="http://simpleinjector.codeplex.com/wikipage?title=Migration%20Guide&amp;referringTitle=Documentation" title="Simple Injector - Migration Guide">migration guide</a>, which helps users that want to switch from <em>Simple Injector</em> to another DI framework. I will describe the lack of support for this feature on the migration page of those frameworks that do.</p><p>I hope developers find the library useful. My intention is to keep it small and simple, and having lots of documentation and code snippets on the CodePlex wiki to keep developers productive. </p><p>Happy injecting!</p>
		]]></content>
		<author>
			<name>Steven</name>
		</author>
	</entry>
	
	
	
	<entry>
		<title>Removing Keyed Registrations from the Simple Service Locator</title>
		<link rel="alternate" type="text/html" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=86" />
		<updated>2011-05-01T16:46:00+02:00</updated>
		<published>2011-03-13T14:17:00+02:00</published>
		<id>tag:pivotpowered,2012:NETJunkie.86</id>
		<link rel="related" type="text/html" href=""  />
		<summary type="text">In this post I again like to consult my Simple Service Locator users,  readers of my blog, and followers of the Simple Service Locator CodePlex  project, about a change to the library I'm considering.</summary>
        <content type="html" xml:lang="en" xml:base="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=86"><![CDATA[
                In this post I again like to consult my Simple Service Locator users,  readers of my blog, and followers of the Simple Service Locator CodePlex  project, about a change to the library I'm considering.<p><img src="http://www.cuttingedge.it/blogs/steven/images/key.jpg" style="float:right;margin-left:10px;margin-bottom:5px;border:1px solid" title="" alt="" class="pivot-image" />Thanks for everybody who replied to my <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=85" title=".NET Junkie's weblog - Do we need the Common Service Locator?">last blog post</a> about the <a rel="external" href="http://simpleservicelocator.codeplex.com/SourceControl/changeset/changes/69741" title="Simple Service Locator">Simple Service Locator</a>. Because of all the reactions, I'm currently seriously considering to loose the hard dependency on the Common Service Locator. I&rsquo;m currently trying to come up with a solution where I can have a soft dependency on de Common Service Locator (by loading the assembly with Assembly.Load and using lightweight code generation to generate a IServiceLocator implementation), but this currently seems very fragile.</p><p>An other thing I'm currently considering is removing the possibility to do keyed registrations (registering instances by a string key). The reason is the same as with removing the hard dependency on the Common Service Locator: I think it makes little sense when doing dependency injection.</p><p>Before making such a change I again want to consult my users and followers. So can you tell me if you are using keyed registrations today in your projects (with the Simple Service Locator or any DI framework for that matter) and have any reason to believe that you can't easily change it to using factories.</p><p>Please drop a note in the comments below or send me a mail (to steven at this domain) if you prefer that.</p><p>Thanks.</p>
		]]></content>
		<author>
			<name>Steven</name>
		</author>
	</entry>
	
	
	
	<entry>
		<title>Do we need the Common Service Locator?</title>
		<link rel="alternate" type="text/html" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=85" />
		<updated>2011-04-01T13:13:00+02:00</updated>
		<published>2011-03-01T20:45:00+02:00</published>
		<id>tag:pivotpowered,2012:NETJunkie.85</id>
		<link rel="related" type="text/html" href=""  />
		<summary type="text">The Simple Service Locator has a hard dependency on the Common Service Locator. But is this a good design choice? I like to hear your opinion on this.</summary>
        <content type="html" xml:lang="en" xml:base="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=85"><![CDATA[
                The Simple Service Locator has a hard dependency on the Common Service Locator. But is this a good design choice? I like to hear your opinion on this.<p><img src="http://www.cuttingedge.it/blogs/steven/images/csl.jpg" style="float:right;margin-left:10px;margin-bottom:5px;border:1px solid" title="Common Service Locator logo" alt="Common Service Locator logo" class="pivot-image" />It's now been over a year ago since I published a first version of the  <a rel="external" href="http://simpleservicelocator.codeplex.com" title="Simple Service Locator">Simple Service Locator</a> project on CodeProject. The Simple Service  Locator was (and still is) meant as an intermediate IoC framework,  especially suited for developers that are new to IoC and are not yet  familiar with any of the big (more complicated) IoC frameworks in the  field. One of the core design goals behind the library was to make an  IoC implementation that could easily be replaced it with a more  feature-rich IoC framework when needed. Because of this I let the  library have a hard dependency on the <a rel="external" href="http://commonservicelocator.codeplex.com/wikipage?title=API%20Reference&amp;referringTitle=Implementing%20the%20Interface" title="Common Service Locator - an abstraction over IoC implementations">Common Service Locator</a>.</p><p>It was not much later after releasing that first beta of the SSL that I started to doubt the usefulness of having a dependency on the Common Service Locator. The reason for it was that I (finally) started to see the benefits of writing applications in such a way that the dependency on a DI framework or an abstraction over it, could be removed altogether. By using the <a rel="external" href="http://dotnetslackers.com/articles/designpatterns/DI-Patterns-Constructor-Injection.aspx" title="DI Design Pattern: Constructor Injection">constructor injection</a> DI pattern, instead of calling a container or an abstraction over it directly from code (which is known as the <a rel="external" href="http://java.sun.com/blueprints/corej2eepatterns/Patterns/ServiceLocator.html" title="Service Locator">Service Locator</a> (<a rel="external" href="http://blog.ploeh.dk/2010/02/03/ServiceLocatorIsAnAntiPattern.aspx" title="Mark Seemann's .NET blog - Service Locator is an Anti-Pattern">anti</a>) pattern), we are able to almost completely hide the used IoC container from the application. Ideally there should be just a single line of code in the application that calls the container. Having a project structured like that, makes the need of using an abstraction redundant, because what's the use of an abstraction when you can replace it with one line of code?</p><p>I noticed that writing unit tests became much easier after I choose to use Dependency Injection over the Service Locator pattern. In the past I had a lot of nasty IoC configuration for my unit tests. I had to do clever tricks to make them run correctly in parallel (because MSTest runs tests in parallel).</p><p>The thing is however, that when you start writing unit tests for a code base that contains no tests yet, starting of with the Service Locator pattern is a hell of a lot easier than using the Dependency Injection pattern. When you start using dependency injection, you move the responsibility of wiring the dependencies together from a class up to its consumers. The consumers again will have to move the wiring to their consumers. In other words, when applying  DI, it tends to have a ripple effect bottom up through your code base. To get an existing project structured like that, you probably need to refactor a lot. </p><p>Because of this I was (and still am) in doubt about whether forcing my users to have a dependency on the Common Service Locator is good thing, because a good designed application won't need it. On the other hand, because SSL is meant as an intermediate IoC framework, the library will probably be used as first IoC framework, and developers are likely to pick Service Locator over Dependency Injection.</p><p style="border: 4px solid blue; padding: 4px"><font color="#0000ff">Because of this doubt, I like to turn to you, my users of the Simple Service Locator, followers of the CodePlex project, and readers of my blog. If you are using SSL today, I like to know if you are benefitting from the Common Service Locator facade or if it's in your way. What are your thoughts about this subject? Do you think that having an hard dependency on the Common Service Locator is justifiable, or would the library benefit from being published without the Common Service Locator?</font></p><p>Please drop a note in the comments below or send me a mail (to steven at this domain) if you prefer that.</p><p>Thanks in advance.</p> <p>Cheers</p>
		]]></content>
		<author>
			<name>Steven</name>
		</author>
	</entry>
	
	
	
	<entry>
		<title>Faking your LINQ provider part 1</title>
		<link rel="alternate" type="text/html" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=84" />
		<updated>2011-12-08T13:08:00+02:00</updated>
		<published>2010-11-14T15:40:00+02:00</published>
		<id>tag:pivotpowered,2012:NETJunkie.84</id>
		<link rel="related" type="text/html" href=""  />
		<summary type="text">I recently tried to figure out how to write testable code while using LINQ to SQL as my O/RM of choice, without loosing the ability to use LINQ to Expression trees! In this post I describe the design I ender up with.</summary>
        <content type="html" xml:lang="en" xml:base="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=84"><![CDATA[
                I recently tried to figure out how to write testable code while using LINQ to SQL as my O/RM of choice, without loosing the ability to use LINQ to Expression trees! In this post I describe the design I ender up with.<p><img src="http://www.cuttingedge.it/blogs/steven/images/chain.jpg" style="float:right;margin-left:10px;margin-bottom:5px;border:1px solid" title="" alt="" class="pivot-image" />Friday, someone at <a rel="external" href="http://www.stackoverflow.com">Stackoverflow</a> <a rel="external" href="http://stackoverflow.com/questions/4169839/repository-pattern-with-modern-data-access-strategies" title="Repository pattern with ">asked</a> how to hide LINQ enabled persistence frameworks behind an abstraction (the <a rel="external" href="http://martinfowler.com/eaaCatalog/repository.html">repository pattern</a>). I pointed him to <a rel="external" href="http://stackoverflow.com/questions/4128640/how-to-remove-unit-of-work-functionality-from-repositories-using-ioc" title="How to remove unit of work functionality from repositories using IOC">a question</a> on Stackoverflow that I answered a few days earlier in what I explained how to allow your LINQ to SQL project to be unit testable. Friday&rsquo;s question however, was about being able to easily change the <a rel="external" href="http://en.wikipedia.org/wiki/Object-relational_mapping" title="Object-relational mapping">O/RM</a> later on, and specifically with multiple data stores / databases involved.</p>  <p>Let me start by saying that due to the current difference in behavior and quality between both open source and commercial LINQ provider implementations, it is hard to completely abstract away such implementation, while still allowing to use LINQ to Expression queries that are effectively translated to database queries. If you want to be able to easily switch O/RM technology later on, you should -not only- have enough unit tests, but especially have enough integration tests that verify the interaction between your LINQ queries and the database (with the persistence technology in between). Also business transactions that involve deletes are something you should cover using integration tests, because the behavior of deleting objects might differ between O/RM frameworks in surprising ways.</p>  <p>For the project I'm currently working on, I use LINQ to SQL as O/RM tool and I was faced with the problem of unit testing. I wrote <a rel="external" href="http://stackoverflow.com/questions/4128640/how-to-remove-unit-of-work-functionality-from-repositories-using-ioc" title="How to remove unit of work functionality from repositories using IOC">this answer</a> on Stackoverflow with the experience gained on this project. The answer explains a simplified model of what I designed. What that answer didn&rsquo;t show however, was that my actual solution was especially designed to deal with multiple data sources. Friday&rsquo;s answer triggered me to write this actual design down. What I tried to achieve was the following:</p>  <ul> <li>Abstracting LINQ to SQL away enough to allow unit testing.</li> <li>Create the abstractions in such a way that adding new entities and new data sources would take very little code, both in application and tests.</li> <li>I wanted it to be as <a rel="external" href="http://en.wikipedia.org/wiki/Don%27t_repeat_yourself" title="Don't repeat yourself">DRY</a> as a bone.</li> <li>Have a model that closely mimics the API of LINQ to SQL.</li> </ul>  <p>What I tried to achieve in my design was to have one unit of work per data source, but without the need to have different implementations during testing. What I ended up with was a design were the persistence technology was abstracted away behind an <span class="type">IDataMapper</span> interface. The unit of work class would be dependent on the <span class="type">IDataMapper</span>, but not on the specific O/RM.</p>  <p>In my design the unit of work would be a container of repositories. These repositories would simply implement <span class="type">IQueryable</span><span class="code">&lt;T&gt;</span> (such as <span class="type">IQueryable</span><span class="code">&lt;</span><span class="type">Customer</span><span class="code">&gt;</span> for a customer repository), because this allows us to use LINQ queries over the repository.</p>  <p>The typical caller of those data source specific unit of work classes would be a business command or service class. While I could easily configure <a rel="external" href="http://simpleinjector.codeplex.com" target="_blank" title="Simple Injector - The easiest IoC framework in town.">my favorite IoC framework</a> to create a new instance of a unit of work and inject it into a command, I liked the creation of a new unit of work to be more explicit. Units of work should be committed and disposed, which makes the ownership important. I wanted to make creation and disposing of those object very explicit in my code. For this reason I decided to write factories for the creation of units of work.</p>  <p>Let&rsquo;s go through the different parts of the code, starting with the Units of work:</p>  <h5>Unit of Work<a name="unit_of_work" title="unit_of_work"></a></h5>  <p>The <a rel="external" href="http://martinfowler.com/eaaCatalog/unitOfWork.html">Unit of Work</a> pattern describes a way to coordinate the writing out of changes in a business transaction. It allows you to make a series of changes in memory and commit them atomically. In my design I have a class per data source. For instance, below is an example of a unit of work for the Northwind database:</p>  <pre class="cs" language="csharp" customtypes="Assert Customer DataContext Employee EntityContainer EntityFrameworkDataMapper EntityFrameworkNorthwindUnitOfWorkFactory EntityFrameworkSalesUnitOfWorkFactory EntityRepository Expression FakeFactory FakeUnitOfWorkFactoryFactory IBusinessCommand IDataMapper InMemoryDataMapper InMemoryRepository IQueryable IQueryProvider DebuggerStepThrough IUnitOfWorkFactory KeyNotFoundException LinqToSqlDataMapper LinqToSqlNorthwindUnitOfWorkFactory LinqToSqlRepository NorthwindRepositoryExtensions NorthwindUnitOfWork Order Repository SalesUnitOfWork SomeBusinessCommand SomeBusinessCommandHandler IHandle Table">public sealed class NorthwindUnitOfWork : IDisposable <br />{<br />    private readonly IDataMapper mapper;<br />    <br />    public NorthwindUnitOfWork(IDataMapper mapper)<br />    {<br />        this.mapper = mapper;<br />    }<br />    <br />    public Repository&lt;Customer&gt; Customers<br />    {<br />        [DebuggerStepThrough]<br />        get { return this.mapper.GetRepository&lt;Customer&gt;(); }<br />    }<br />    <br />    public Repository&lt;Employee&gt; Employees<br />    {<br />        [DebuggerStepThrough]<br />        get { return this.mapper.GetRepository&lt;Employee&gt;(); }<br />    }<br />    <br />    public Repository&lt;Order&gt; Orders<br />    {<br />        [DebuggerStepThrough]<br />        get { return this.mapper.GetRepository&lt;Order&gt;(); }<br />    }<br />    <br />    [DebuggerStepThrough]<br />    public void SubmitChanges()<br />    {<br />        this.mapper.Save();<br />    }<br />    <br />    [DebuggerStepThrough]<br />    public void Dispose()<br />    {<br />        this.mapper.Dispose();<br />    }<br />}</pre>  <p>The <span class="type">NorthwindUnitOfWork</span> wraps a <span class="type">IDataMapper</span> and forwards the calls to <span class="code">Dispose</span> and <span class="code">SubmitChanges</span> to the mapper. The <span class="type">NorthwindUnitOfWork</span> also contains a set of properties that represent the different repositories. A repository implements <span class="type">IQueryable</span><span class="code">&lt;T&gt;</span> and allows the retrieval of a certain type. As you can see, all properties return the generic <span class="type">Repository</span><span class="code">&lt;T&gt;</span> class. Here is the definition of <span class="type">Repository</span><span class="code">&lt;T&gt;</span>:</p>  <pre class="cs" language="csharp" customtypes="Assert Customer DataContext Employee EntityContainer EntityFrameworkDataMapper EntityFrameworkNorthwindUnitOfWorkFactory EntityFrameworkSalesUnitOfWorkFactory EntityRepository Expression FakeFactory FakeUnitOfWorkFactoryFactory IBusinessCommand IDataMapper InMemoryDataMapper InMemoryRepository IQueryable IQueryProvider IUnitOfWorkFactory KeyNotFoundException LinqToSqlDataMapper LinqToSqlNorthwindUnitOfWorkFactory LinqToSqlRepository NorthwindRepositoryExtensions NorthwindUnitOfWork Order Repository SalesUnitOfWork SomeBusinessCommand Table">public abstract class Repository&lt;T&gt; : IQueryable&lt;T&gt;<br />    where T : class<br />{<br />    private readonly IQueryable&lt;T&gt; query;<br /><br />    protected Repository(IQueryable&lt;T&gt; query)<br />    {<br />        this.query = query;<br />    }<br /><br />    public Type ElementType<br />    {<br />        get { return this.query.ElementType; }<br />    }<br /><br />    public Expression Expression<br />    {<br />        get { return this.query.Expression; }<br />    }<br /><br />    public virtual IQueryProvider Provider<br />    {<br />        get { return this.query.Provider; }<br />    }<br /><br />    public abstract void InsertOnSubmit(T entity);<br /><br />    public abstract void DeleteOnSubmit(T entity);<br /><br />    public void InsertAllOnSubmit(IEnumerable&lt;T&gt; entities)<br />    {<br />        foreach (var entity in entities)<br />        {<br />            this.InsertOnSubmit(entity);<br />        }<br />    }<br /><br />    public void DeleteAllOnSubmit(IEnumerable&lt;T&gt; entities)<br />    {<br />        foreach (var entity in entities)<br />        {<br />            this.DeleteOnSubmit(entity);<br />        }<br />    }<br /><br />    public IEnumerator&lt;T&gt; GetEnumerator()<br />    {<br />        return this.query.GetEnumerator();<br />    }<br /><br />    IEnumerator IEnumerable.GetEnumerator()<br />    {<br />        return this.query.GetEnumerator();<br />    }<br />}</pre>  <p>The repository decorates an <span class="type">IQueryable</span><span class="code">&lt;T&gt;</span>. The sole reason to have a <span class="type">Repository</span><span class="code">&lt;T&gt;</span> instead of simply returning <span class="type">IQueryable</span><span class="code">&lt;T&gt;</span> is because of the <span class="code">InsertOnSubmit</span> and <span class="code">DeleteOnSubmit</span> methods. In my initial design I implemented the <span class="code">InsertOnSubmit</span> and <span class="code">DeleteOnSubmit</span> as instance methods of the unit of work (as Entity Framework does). However, when I added <span class="code">InsertAllOnSubmit</span> and <span class="code">DeleteAllOnSubmit</span> methods things went wrong. I wrote code that looked a bit like this:</p>  <pre class="cs" language="csharp" customtypes="Assert Customer DataContext Employee EntityContainer EntityFrameworkDataMapper EntityFrameworkNorthwindUnitOfWorkFactory EntityFrameworkSalesUnitOfWorkFactory EntityRepository Expression FakeFactory FakeUnitOfWorkFactoryFactory IBusinessCommand IDataMapper InMemoryDataMapper InMemoryRepository IQueryable IQueryProvider IUnitOfWorkFactory KeyNotFoundException LinqToSqlDataMapper LinqToSqlNorthwindUnitOfWorkFactory LinqToSqlRepository NorthwindRepositoryExtensions NorthwindUnitOfWork Order Repository SalesUnitOfWork SomeBusinessCommand Table">var customer =<br />    context.Customers.GetById(this.CustomerId);<br /> <br />context.DeleteOnSubmit(customer.Orders);</pre>  <p>Note that I incorrectly called <span class="code">DeleteOnSubmit</span> instead of calling the <span class="code">Delete<strong>All</strong>OnSubmit</span>. This compiled fine, because <span class="code">DeleteOnSubmit</span> accepted <span class="keyword">object</span> and a collection of orders is of course an <span class="keyword">object</span>. I think this was one of the reasons why the C# team decided to put those insert and delete methods on LINQ to SQL&rsquo;s <span class="type">Table</span><span class="code">&lt;T&gt;</span> class. So I wanted to have those methods on the repository and that lead to a design with the <span class="type">Repository</span><span class="code">&lt;T&gt;</span> class.</p>  <p>The <span class="type">NorthwindUnitOfWork</span> and the <span class="type">Repository</span><span class="code">&lt;T&gt;</span> together now mimic the LINQ to SQL API very closely. Because of this, for the most part I didn&rsquo;t have to change my code to get this to work, with is a big plus when you want to add this to an existing project.</p>  <p>Having an API close to that of LINQ to SQL wasn&rsquo;t enough for me however. The idea of the Repository pattern is to have entity specific operations that allow fetching or deleting entities of a certain type such as <span class="code">GetOrderById</span> or <span class="code">FindCustomerByName</span>. In the past I already solved this problem by writing these operations as extension methods on <span class="type">Table</span><span class="code">&lt;</span><span class="type">Order</span><span class="code">&gt;</span> and <span class="type">Table</span><span class="code">&lt;</span><span class="type">Customer</span><span class="code">&gt;</span>. By writing extension methods on IQueryable<span class="code">&lt;</span><span class="type">Order</span><span class="code">&gt;</span> and <span class="type">IQueryable</span><span class="code">&lt;</span><span class="type">Customer</span><span class="code">&gt;</span> -from a user&rsquo;s perspective- it is just as if these methods are defined on the repository itself:</p>  <pre class="cs" language="csharp" customtypes="Assert Customer DataContext Employee EntityContainer EntityFrameworkDataMapper EntityFrameworkNorthwindUnitOfWorkFactory EntityFrameworkSalesUnitOfWorkFactory EntityRepository Expression FakeFactory FakeUnitOfWorkFactoryFactory IBusinessCommand IDataMapper InMemoryDataMapper InMemoryRepository IQueryable IQueryProvider IUnitOfWorkFactory KeyNotFoundException LinqToSqlDataMapper LinqToSqlNorthwindUnitOfWorkFactory LinqToSqlRepository NorthwindRepositoryExtensions NorthwindUnitOfWork Order Repository SalesUnitOfWork SomeBusinessCommand Table">public static class NorthwindRepositoryExtensions<br />{<br />    public static Customer GetById(<br />        this IQueryable&lt;Customer&gt; repository, string id)<br />    {<br />        return GetSingle(repository, e =&gt; e.Id == id, id);<br />    }<br /><br />    public static Employee GetById(<br />        this IQueryable&lt;Employee&gt; repository, int id)<br />    {<br />        return GetSingle(repository, e =&gt; e.Id == id, id);<br />    }<br /><br />    public static Order GetById(<br />        this IQueryable&lt;Order&gt; repository, int id)<br />    {<br />        return GetSingle(repository, e =&gt; e.Id == id, id);<br />    }<br /><br />    // TODO: More GetById methods here.<br /><br />    // Allow reporting more descriptive error messages.<br />    private static T GetSingle&lt;T&gt;(IQueryable&lt;T&gt; collection, <br />        Expression&lt;Func&lt;T, bool&gt;&gt; predicate, object id)<br />        where T : class<br />    {<br />        T entity;<br /><br />        try<br />        {<br />            entity = collection.SingleOrDefault(predicate);<br />        }<br />        catch (Exception ex)<br />        {<br />            throw new InvalidOperationException(string.Format(<br />                &quot;There was an error retrieving an {0} with &quot; +<br />                &quot;id {1}. {2}&quot;,<br />                typeof(T).Name, id ?? &quot;{null}&quot;, ex.Message), ex);<br />        }<br /><br />        if (entity == null)<br />        {<br />            throw new KeyNotFoundException(string.Format(<br />                &quot;{0} with id {1} was not found.&quot;, <br />                typeof(T).Name, id ?? &quot;{null}&quot;));<br />        }<br /><br />        return entity;<br />    }<br />}</pre>  <p>While it would be sufficient to implement those <span class="code">GetById</span> methods with <span class="keyword">return</span><span class="code"> repository.Single(e =&gt; e.Id == id)</span>, I found out quickly that this would give very little information on failure. A private method that throws a more descriptive exception was the solution.</p>  <h5>Data Mapper<a name="data_mapper" title="data_mapper"></a></h5>  <p>To keep the unit of work classes, such as <span class="type">NorthwindUnitOfWork</span>, ignorant to the chosen technology, a mapping should be in place between that type and the used persistence framework. This is what the <span class="type">IDataMapper</span> interface is for:</p>  <pre class="cs" language="csharp" customtypes="Assert Customer DataContext Employee EntityContainer EntityFrameworkDataMapper EntityFrameworkNorthwindUnitOfWorkFactory EntityFrameworkSalesUnitOfWorkFactory EntityRepository Expression FakeFactory FakeUnitOfWorkFactoryFactory IBusinessCommand IDataMapper InMemoryDataMapper InMemoryRepository IQueryable IQueryProvider IUnitOfWorkFactory KeyNotFoundException LinqToSqlDataMapper LinqToSqlNorthwindUnitOfWorkFactory LinqToSqlRepository NorthwindRepositoryExtensions NorthwindUnitOfWork Order Repository SalesUnitOfWork SomeBusinessCommand Table">public interface IDataMapper : IDisposable<br />{<br />    Repository&lt;T&gt; GetRepository&lt;T&gt;() where T : class;<br /> <br />    void Save();<br />}</pre>  <p>If you look closely at the definition of this interface, you&rsquo;ll notice that the data mapper is in fact a unit of work. As a matter of fact, if you wish, you could just use the <span class="type">IDataMapper</span> directly in your business layer instead of using a <span class="type">NorthwindUnitOfWork</span> and its extension methods. Main reason for the them to exist is syntactic sugar. It makes the code much cleaner. In fact, it&rsquo;s only because <a rel="external" href="http://blogs.msdn.com/b/ericlippert/archive/2009/10/05/why-no-extension-properties.aspx" title="Eric Lippert - Why no extension properties?">C# lacks extension properties</a> that we actually need a <span class="type">NorthwindUnitOfWork</span>.</p>  <p>With the definition of the <span class="type">IDataMapper</span>, it is easy to create implementations for specific O/RM frameworks. Here is an implementation for LINQ to SQL:</p>  <pre class="cs" language="csharp" customtypes="Assert Customer DataContext Employee EntityContainer EntityFrameworkDataMapper EntityFrameworkNorthwindUnitOfWorkFactory EntityFrameworkSalesUnitOfWorkFactory EntityRepository Expression FakeFactory FakeUnitOfWorkFactoryFactory IBusinessCommand IDataMapper InMemoryDataMapper InMemoryRepository IQueryable IQueryProvider IUnitOfWorkFactory KeyNotFoundException LinqToSqlDataMapper LinqToSqlNorthwindUnitOfWorkFactory LinqToSqlRepository NorthwindRepositoryExtensions NorthwindUnitOfWork Order Repository SalesUnitOfWork SomeBusinessCommand Table">public sealed class LinqToSqlDataMapper : IDataMapper<br />{<br />    private readonly DataContext context;<br />    private readonly Dictionary&lt;Type, object&gt; repositories =<br />        new Dictionary&lt;Type, object&gt;();<br /><br />    public LinqToSqlDataMapper(DataContext context)<br />    {<br />        this.context = context;<br />    }<br /><br />    public void Save()<br />    {<br />        this.context.SubmitChanges();<br />    }<br /><br />    public void Dispose()<br />    {<br />        this.context.Dispose();<br />    }<br /><br />    public Repository&lt;T&gt; GetRepository&lt;T&gt;() where T : class<br />    {<br />        object rep;<br /><br />        if (!this.repositories.TryGetValue(typeof(T), out rep))<br />        {<br />            var table = this.context.GetTable&lt;T&gt;();<br />            rep = new LinqToSqlRepository&lt;T&gt;(table);<br />            this.repositories[typeof(T)] = rep;<br />        }<br /><br />        return (Repository&lt;T&gt;)rep;<br />    }<br /><br />    private sealed class LinqToSqlRepository&lt;T&gt; : Repository&lt;T&gt;<br />        where T : class<br />    {<br />        private readonly Table&lt;T&gt; table;<br /><br />        public LinqToSqlRepository(Table&lt;T&gt; table)<br />            : base(table)<br />        {<br />            this.table = table;<br />        }<br /><br />        public override void InsertOnSubmit(T entity)<br />        {<br />            this.table.InsertOnSubmit(entity);<br />        }<br /><br />        public override void DeleteOnSubmit(T entity)<br />        {<br />            this.table.DeleteOnSubmit(entity);<br />        }<br />    }<br />}</pre>  <p>As you can see, the <span class="type">LinqToSqlDataMapper</span> wraps a LINQ to SQL <span class="type">DataContext</span> class and forwards it&rsquo;s Save and Dispose methods to the <span class="type">DataContext</span>. Its <span class="code">GetRepository&lt;T&gt;</span> method returns <span class="type">LinqToSqlRepository</span><span class="code">&lt;T&gt;</span> classes, which wrap <span class="type">Table</span><span class="code">&lt;T&gt;</span> instances. As you can see, the code is fairly simple.</p>  <p>A bit more tricky is the implementation for Entity Framework:</p>  <pre class="cs" language="csharp" customtypes="ObjectQuery ObjectContext Assert Customer DataContext Employee EntityContainer EntityFrameworkDataMapper EntityFrameworkNorthwindUnitOfWorkFactory EntityFrameworkSalesUnitOfWorkFactory EntityRepository Expression FakeFactory FakeUnitOfWorkFactoryFactory IBusinessCommand IDataMapper InMemoryDataMapper InMemoryRepository IQueryable IQueryProvider IUnitOfWorkFactory KeyNotFoundException LinqToSqlDataMapper LinqToSqlNorthwindUnitOfWorkFactory LinqToSqlRepository NorthwindRepositoryExtensions NorthwindUnitOfWork Order Repository SalesUnitOfWork SomeBusinessCommand Table" customvaluetypes="DataSpace">public sealed class EntityFrameworkDataMapper : IDataMapper<br />{<br />    private readonly ObjectContext context;<br />    private readonly Dictionary&lt;Type, object&gt; repositories =<br />        new Dictionary&lt;Type, object&gt;();<br /><br />    public EntityFrameworkDataMapper(ObjectContext context)<br />    {<br />        this.context = context;<br />    }<br /><br />    public void Save()<br />    {<br />        this.context.SaveChanges();<br />    }<br /><br />    public void Dispose()<br />    {<br />        this.context.Dispose();<br />    }<br /><br />    public Repository&lt;T&gt; GetRepository&lt;T&gt;() where T : class<br />    {<br />        object rep;<br /><br />        if (!this.repositories.TryGetValue(typeof(T), out rep))<br />        {<br />            string setName = this.GetEntitySetName&lt;T&gt;();<br /><br />            var query = this.context.CreateQuery&lt;T&gt;(setName);<br />            rep = new EntityRepository&lt;T&gt;(query, setName);<br />            this.repositories[typeof(T)] = rep;<br />        }<br /><br />        return (Repository&lt;T&gt;)rep;<br />    }<br /><br />    private string GetEntitySetName&lt;T&gt;()<br />    {<br />        EntityContainer container =<br />            this.context.MetadataWorkspace.GetEntityContainer(<br />            this.context.DefaultContainerName, DataSpace.CSpace);<br /><br />        return (<br />            from item in container.BaseEntitySets<br />            where item.ElementType.Name == typeof(T).Name<br />            select item.Name).First();<br />    }<br /><br />    private sealed class EntityRepository&lt;T&gt;<br />        : Repository&lt;T&gt; where T : class<br />    {<br />        private readonly ObjectQuery&lt;T&gt; query;<br />        private readonly string entitySetName;<br /><br />        public EntityRepository(ObjectQuery&lt;T&gt; query,<br />            string entitySetName)<br />            : base(query)<br />        {<br />            this.query = query;<br />            this.entitySetName = entitySetName;<br />        }<br /><br />        public override void InsertOnSubmit(T entity)<br />        {<br />            this.query.Context.AddObject(entitySetName, entity);<br />        }<br /><br />        public override void DeleteOnSubmit(T entity)<br />        {<br />            this.query.Context.DeleteObject(entity);<br />        }<br />    }<br />}</pre>  <p>For Entity Framework you need to do a bit more work to create repositories, because Entity Framework expects you to supply the entity set name, which would normally the plural form of the entity name, but can in fact be anything. This entity set name is also needed for inserting entities. As you can see, the internal <span class="type">EntityRepository</span><span class="code">&lt;T&gt;</span> forwards insert and delete calls back to the context, because that&rsquo;s how Entity Framework likes it (but I don&rsquo;t).</p><p><font color="#FF0000">UPDATE: </font>Note that the ObjectSet&lt;T&gt; class of Entity Framework 4.0 now contains a AddObject(T) method (which was missing in .NET 3.5), which makes writing the EntityResository&lt;T&gt; much easier.</p>  <p>For unit testing we of course want to have an in-memory representation of the objects:</p>  <pre class="cs" language="csharp" customtypes="Assert Customer DataContext Employee EntityContainer EntityFrameworkDataMapper EntityFrameworkNorthwindUnitOfWorkFactory EntityFrameworkSalesUnitOfWorkFactory EntityRepository Expression FakeFactory FakeUnitOfWorkFactoryFactory IBusinessCommand IDataMapper InMemoryDataMapper InMemoryRepository IQueryable IQueryProvider IUnitOfWorkFactory KeyNotFoundException LinqToSqlDataMapper LinqToSqlNorthwindUnitOfWorkFactory LinqToSqlRepository NorthwindRepositoryExtensions NorthwindUnitOfWork Order Repository SalesUnitOfWork SomeBusinessCommand Table">public class InMemoryDataMapper : IDataMapper<br />{<br />    private List&lt;object&gt; committed = new List&lt;object&gt;();<br />    private List&lt;object&gt; uncommittedInserts = new List&lt;object&gt;();<br />    private List&lt;object&gt; uncommittedDeletes = new List&lt;object&gt;();<br /><br />    public bool Saved { get; private set; }<br /><br />    public bool Disposed { get; private set; }<br /><br />    // Get a list with all committed objects of type T.<br />    public IEnumerable&lt;T&gt; Committed&lt;T&gt;() where T : class<br />    {<br />        return this.committed.OfType&lt;T&gt;();<br />    }<br /><br />    public void AddCommitted(object entity)<br />    {<br />        this.committed.Add(entity);<br />    }<br /><br />    public Repository&lt;T&gt; GetRepository&lt;T&gt;() where T : class<br />    {<br />        return new InMemoryRepository&lt;T&gt;(this);<br />    }<br /><br />    public void Save()<br />    {<br />        this.committed.AddRange(this.uncommittedInserts);<br />        this.uncommittedInserts.Clear();<br /><br />        this.committed.RemoveAll(<br />            e =&gt; this.uncommittedDeletes.Contains(e));<br />        this.uncommittedDeletes.Clear();<br /><br />        this.Saved = true;<br />    }<br /><br />    public void Dispose()<br />    {<br />        this.Disposed = true;<br />    }<br /><br />    private sealed class InMemoryRepository&lt;T&gt; : Repository&lt;T&gt;<br />        where T : class<br />    {<br />        private readonly InMemoryDataMapper mapper;<br /><br />        public InMemoryRepository(InMemoryDataMapper mapper)<br />            : base(mapper.committed.OfType&lt;T&gt;().AsQueryable())<br />        {<br />            this.mapper = mapper;<br />        }<br /><br />        public override void InsertOnSubmit(T entity)<br />        {<br />            if (this.mapper.committed.Contains(entity))<br />                Assert.Fail(&quot;Entity already exist.&quot;);<br /><br />            this.mapper.uncommittedInserts.Add(entity);<br />        }<br /><br />        public override void DeleteOnSubmit(T entity)<br />        {<br />            if (!this.mapper.committed.Contains(entity))<br />                Assert.Fail(&quot;Entity does not exist.&quot;);<br /><br />            this.mapper.uncommittedDeletes.Add(entity);<br />        }<br />    }<br />}</pre>  <p>The <span class="code">AddCommitted</span> method is especially useful during test setup. You typically want to configure the <span class="type">InMemoryDataMapper</span> with a set of committed objects. This correctly mimics how LINQ to SQL and Entity Framework work. The <span class="code">Committed&lt;T&gt;()</span> method is useful during the assertion phase of your tests. With this method you can check if the objects you expect are indeed committed.</p>  <h5>Unit of Work factories<a name="unit_of_work_factories" title="unit_of_work_factories"></a></h5>  <p>The last piece of the puzzle are the Unit of Work factories. Each unit of work gets it&rsquo;s own factory. As I explained,  I like the creation of objects that implement <span class="type">IDisposable</span> to be very explicit. Factories help with this.</p>  <p>In my project I had to deal with multiple data stores. To minimize the number of needed interfaces I decided to define a single generic interface for creating unit of work classes:</p>  <pre class="cs" language="csharp" customtypes="Assert Customer DataContext Employee EntityContainer EntityFrameworkDataMapper EntityFrameworkNorthwindUnitOfWorkFactory EntityFrameworkSalesUnitOfWorkFactory EntityRepository Expression FakeFactory FakeUnitOfWorkFactoryFactory IBusinessCommand IDataMapper InMemoryDataMapper InMemoryRepository IQueryable IQueryProvider IUnitOfWorkFactory KeyNotFoundException LinqToSqlDataMapper LinqToSqlNorthwindUnitOfWorkFactory LinqToSqlRepository NorthwindRepositoryExtensions NorthwindUnitOfWork Order Repository SalesUnitOfWork SomeBusinessCommand Table">public interface IUnitOfWorkFactory&lt;TUnitOfWork&gt;<br />{<br />    TUnitOfWork CreateNew();<br />}</pre>  <p>While there is one generic interface, you&rsquo;ll still need to have one concrete factory for the chosen persistence technology. For instance, here is the factory for creating <span class="type">NorthwindUnitOfWork</span> instances with LINQ to SQL:</p>  <pre class="cs" language="csharp" customtypes="MappingSource AttributeMappingSource Assert Customer DataContext Employee EntityContainer EntityFrameworkDataMapper EntityFrameworkNorthwindUnitOfWorkFactory EntityFrameworkSalesUnitOfWorkFactory EntityRepository Expression FakeFactory FakeUnitOfWorkFactoryFactory IBusinessCommand IDataMapper InMemoryDataMapper InMemoryRepository IQueryable IQueryProvider IUnitOfWorkFactory KeyNotFoundException LinqToSqlDataMapper LinqToSqlNorthwindUnitOfWorkFactory LinqToSqlRepository NorthwindRepositoryExtensions NorthwindUnitOfWork Order Repository SalesUnitOfWork SomeBusinessCommand Table">public class LinqToSqlNorthwindUnitOfWorkFactory<br />    : IUnitOfWorkFactory&lt;NorthwindUnitOfWork&gt;<br />{<br />    private static MappingSource Source =<br />        new AttributeMappingSource();<br /><br />    private readonly string conStr;<br /><br />    public LinqToSqlNorthwindUnitOfWorkFactory(string conStr)<br />    {<br />        this.conStr = conStr;<br />    }<br /><br />    public NorthwindUnitOfWork CreateNew()<br />    {<br />        var db = new DataContext(this.conStr, Source);<br />        var mapper = new LinqToSqlDataMapper(db);<br />        return new NorthwindUnitOfWork(mapper);<br />    }<br />}</pre>  <p>What you might notice is that the factory is not only data store specific, but also O/RM specific. I tried to define a technology ignorant <span class="type">NorthwindUnitOfWorkFactory</span> by creating  an <span class="type">IDataMapperFactory</span> interface, but unfortunately this didn&rsquo;t work out. For performance reasons, the unit of work factory needs a static <span class="type">MappingSource</span> that is specific to the actual data store. Entity Framework has the same sort of constraint. It needs a default container name which is specific to the data store. Because of this it isn&rsquo;t possible to extract this code to a <span class="type">IDataMapperFactory</span> implementation.</p>  <p>Here is the factory when using Entity Framework:</p>  <pre class="cs" language="csharp" customtypes="ObjectContext Assert Customer DataContext Employee EntityContainer EntityFrameworkDataMapper EntityFrameworkNorthwindUnitOfWorkFactory EntityFrameworkSalesUnitOfWorkFactory EntityRepository Expression FakeFactory FakeUnitOfWorkFactoryFactory IBusinessCommand IDataMapper InMemoryDataMapper InMemoryRepository IQueryable IQueryProvider IUnitOfWorkFactory KeyNotFoundException LinqToSqlDataMapper LinqToSqlNorthwindUnitOfWorkFactory LinqToSqlRepository NorthwindRepositoryExtensions NorthwindUnitOfWork Order Repository SalesUnitOfWork SomeBusinessCommand Table">public class EntityFrameworkNorthwindUnitOfWorkFactory<br />    : IUnitOfWorkFactory&lt;NorthwindUnitOfWork&gt;<br />{<br />    public NorthwindUnitOfWork CreateNew()<br />    {<br />        var db = new ObjectContext(&quot;name=NorthwindEntities&quot;);<br />        db.DefaultContainerName = &quot;NorthwindEntities&quot;;<br />        var mapper = new EntityFrameworkDataMapper(db);<br />        return new NorthwindUnitOfWork(mapper);<br />    }<br />}</pre>  <p>Because constructing units of work in a unit testing environment is much simpler, we don&rsquo;t need a factory per data store. We can simply create a factory for creating unit of work factories :-). The <span class="code">CreateFactory</span> method creates a factory that returns the supplied unit of work:</p>  <pre class="cs" language="csharp" customtypes="Assert Customer DataContext Employee EntityContainer EntityFrameworkDataMapper EntityFrameworkNorthwindUnitOfWorkFactory EntityFrameworkSalesUnitOfWorkFactory EntityRepository Expression FakeFactory FakeUnitOfWorkFactoryFactory IBusinessCommand IDataMapper InMemoryDataMapper InMemoryRepository IQueryable IQueryProvider IUnitOfWorkFactory KeyNotFoundException LinqToSqlDataMapper LinqToSqlNorthwindUnitOfWorkFactory LinqToSqlRepository NorthwindRepositoryExtensions NorthwindUnitOfWork Order Repository SalesUnitOfWork SomeBusinessCommand Table">public static class FakeUnitOfWorkFactoryFactory<br />{<br />    public static IUnitOfWorkFactory&lt;TUnitOfWork&gt;<br />        CreateFactory&lt;TUnitOfWork&gt;(TUnitOfWork uow)<br />    {<br />        return new FakeFactory&lt;TUnitOfWork&gt;()<br />        {<br />            UnitOfWork = uow<br />        };<br />    }<br /><br />    private sealed class FakeFactory&lt;TUnitOfWork&gt;<br />        : IUnitOfWorkFactory&lt;TUnitOfWork&gt;<br />    {<br />        public TUnitOfWork UnitOfWork { get; set; }<br /><br />        public TUnitOfWork CreateNew()<br />        {<br />            return this.UnitOfWork;<br />        }<br />    }<br />}</pre>  <h5>IoC Configuration<a name="ioc_configuration" title="ioc_configuration"></a></h5>  <p>With all this plumbing in place we can now configure our IoC framework. The configuration is really straightforward, because we only need to register the concrete unit of work factories, as follows:</p>  <pre class="cs" language="csharp" customtypes="Assert Customer DataContext Employee EntityContainer EntityFrameworkDataMapper EntityFrameworkNorthwindUnitOfWorkFactory EntityFrameworkSalesUnitOfWorkFactory EntityRepository Expression FakeFactory FakeUnitOfWorkFactoryFactory IBusinessCommand IDataMapper InMemoryDataMapper InMemoryRepository IQueryable IQueryProvider IUnitOfWorkFactory KeyNotFoundException LinqToSqlDataMapper LinqToSqlNorthwindUnitOfWorkFactory LinqToSqlRepository NorthwindRepositoryExtensions NorthwindUnitOfWork Order Repository SalesUnitOfWork SomeBusinessCommand Table">string northwindConnection = GetConStr(&quot;Northwind&quot;);<br /> <br />container.RegisterSingle&lt;IUnitOfWorkFactory&lt;NorthwindUnitOfWork&gt;&gt;(<br />    new LinqToSqlNorthwindUnitOfWorkFactory(northwindConnection));<br /> <br />container.RegisterSingle&lt;IUnitOfWorkFactory&lt;SalesUnitOfWork&gt;&gt;(<br />    new EntityFrameworkSalesUnitOfWorkFactory());</pre>  <h5>Application code<a name="application_code" title="application_code"></a></h5>  <p>I almost forgot the reason why we developers got paid: To create code that helps the business. This is what some business command might look like when we use this code:</p>  <pre class="cs" language="csharp" customtypes="Assert DataContext Employee EntityContainer EntityFrameworkDataMapper EntityFrameworkNorthwindUnitOfWorkFactory EntityFrameworkSalesUnitOfWorkFactory EntityRepository Expression FakeFactory FakeUnitOfWorkFactoryFactory IBusinessCommand IDataMapper InMemoryDataMapper InMemoryRepository IQueryable IQueryProvider IUnitOfWorkFactory KeyNotFoundException LinqToSqlDataMapper LinqToSqlNorthwindUnitOfWorkFactory LinqToSqlRepository NorthwindRepositoryExtensions NorthwindUnitOfWork Order Repository SalesUnitOfWork SomeBusinessCommand SomeBusinessCommandHandler IHandle Table">public class SomeBusinessCommand<br />{<br />    public string CustomerId { get; set; }<br />}<br /><br />public class SomeBusinessCommandHandler<br />    : IHandle&lt;SomeBusinessCommand&gt;<br />{<br />    private IUnitOfWorkFactory&lt;NorthwindUnitOfWork&gt; factory;<br /> <br />    public SomeBusinessCommandHandler(<br />        IUnitOfWorkFactory&lt;NorthwindUnitOfWork&gt; factory)<br />    {<br />        this.factory = factory;<br />    }<br /> <br />    public void Handle(SomeBusinessCommand command)<br />    {<br />        // Create a new context using the factory<br />        using (var context = this.factory.CreateNew())<br />        {<br />            // Using the extension methods on Repository&lt;T&gt;<br />            var customer = <br />                context.Customers.GetById(command.CustomerId);<br /> <br />            // Use LINQ queries to effectively filter data. <br />            var ordersToDelete =<br />                from order in context.Orders<br />                where order.Customer == customer<br />                where order.ShippedDate == null<br />                select order;<br /> <br />            // Use the delete operation on Repository&lt;T&gt;<br />            context.Orders.DeleteAllOnSubmit(ordersToDelete);<br /> <br />            // save the changes to the database<br />            context.SubmitChanges();<br />        }<br />    }<br />} <br /></pre>    <p><font color="#FF0000"><span style="background-color: #ffffff">UPDATE 2011-12-01: <font color="#000000">Although letting handlers create unit of work instances (using a factory) is an explicit model that is easy model to grasp, I came to the conclusion that this does not scale well. When complexity of the business logic increases, you will find yourself passing the unit of work on to other classes, which makes the code harder to follow. Currently, I rather let the unit of work be created and controlled outside the scope of a handlers and configure my DI container in such way that in a certain scope, the same unit of work is always injected. This doesn't invalidate the use of unit of work factories, since they can still be used by parts of the code that controls the unit of work, but keep in mind that you need to do more infrastructural code (DI wiring) to get this to work correctly.</font></span></font> </p><h5>Short comes<a name="short_comes" title="short_comes"></a></h5><p>Although this code has worked very well for me, there are a few short comes that might interest you. First of all, this code doesn&rsquo;t check if the chosen LINQ provider (LINQ to SQL, Entity Framework) can even execute your queries. During unit testing we actually use the LINQ provider on top of LINQ to Objects. This provider just compiles the Expression tree down to delegates and is able to execute practically any query you give it. Providers that translate the query down to SQL (or anything else for that matter) can&rsquo;t do this. You need to be aware of this and need to write integration tests, or test manually if being able to migrate another persistence framework is a concern. This short come is in fact caused by the concept of LINQ to Expression trees itself. To prevent this you could have your repositories not implement <span class="type">IQueryable</span><span class="code">&lt;T&gt;</span> and locate the LINQ queries inside a technology specific repository (which is the usual thing to do). This however, doesn&rsquo;t solve anything, because you now have code that never runs in unit tests at all, and need to rewrite those classes when you migrate to another technology, or at least you still have to test this code manually. There might be a way around this, by letting your LINQ provider run in the background, and verify the executed queries. However, I never managed to create a working proof of concept of this. </p>  <p>Second short come has to do with the difference in delete behavior between frameworks. NHibernate for instance runs inserts and deletes in the order they are registered. While this sometimes is unpractical, at least this is predictable. LINQ to SQL on the other hand, <a rel="external" href="http://stackoverflow.com/questions/445985/linq-to-sql-execution-order-when-calling-submitchanges">always executes delete statements last</a> what can be quite annoying. Therefore, what might work during unit testing or while running with one framework, might fail with another.</p>  <p>Third, this design does not completely hide the O/RM tool. One of the differences that might bite you is the lazy loading behavior of sub entities. When accessing the <span class="code">Employee</span> property of an <span class="type">Order</span>, LINQ to SQL will load it lazily from the database. Entity Framework 3.5 returns null, unless you explicitly tell it to include it. (This design really stinks, and because of this the default behavior has changed in EF 4.0.) This will practically prevent you from using EF 3.5 with this design. A good way to prevent this is by using POCO objects. LINQ to SQL allows you to use POCOs, but again EF 3.5 does not. Also don&rsquo;t forget that LINQ to SQL only supports a one-to-one mapping between an CLR object and database table, while other O/RM tools allow very complex mappings. For this reason, migrating from LINQ to SQL to EF 4.0 would be much easier than the other way around.</p>  <p><strike>A fourth short come is the lack of possibilities to tune performance. Remember that there is one single <span class="type">Repository</span><span class="code">&lt;T&gt;</span> and all entity specific methods are extension methods. Those extension methods need to operate on <span class="type">IQueryable</span><span class="code">&lt;T&gt;</span>. Because those methods will also be called during testing, you can&rsquo;t tune performance by calling some stored procedure at that point. Doing this would &lsquo;promote&rsquo; your unit tests to integration tests.</strike> <font color="#ff0000">UPDATE 2011-01-27:</font> Compared to what I thought before, performance tuning is possible by injecting <a rel="external" href="http://www.udidahan.com/2007/09/16/fetching-strategy-nhibernate-implementation-available/" title="Udi Dahan -   	 Fetching Strategy Design">fetching strategies</a> into the application.  <font color="#ff0000">UPDATE 2011-06-19:</font> Please read <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=89" title="Faking your LINQ Provider part 2: Optimizing performance with fetching strategies">part 2</a> of this series if you're interested in optimizating performance using fetching strategies.</p>  <p>Yet another short come is that this design does not handle concurrency conflicts. All modern O/RM frameworks have a way to handle (especially) offline optimistic concurrency conflicts. The way they report errors however, and the way you have to deal with conflicts however, differs. If you look closely at the designs of the tools I think you can come up with an API that allows not only reporting (throwing exceptions is the simple part), but also fixing those conflicts. This however, is not something I&rsquo;ve dealt with. I usually let the application blow right in my face in the situation of a concurrency conflict and log that failure.</p><p>A last short come I like to mention is that this method will only help you to replace one LINQ provider with another one. When you swap to Azure for instance, you will probably have no LINQ support (or a very limited one) and transition from one to another will fail. If you want to prevent this you should probably hide the LINQ queries behind interfaces.</p><p>As you might have noticed, most short comes have to do with LINQ being an <a rel="external" href="http://en.wikipedia.org/wiki/Leaky_abstraction" title="Wikipedia - Leaky abstraction">leaky abstraction</a>. </p><p><font color="#ff0000">UPDATE 2010-11-18:<font color="#000000"> <a rel="external" href="http://damieng.com/" title="DamienG's blog">Damien</a> wrote earlier this year <a rel="external" href="http://damieng.com/blog/2010/05/21/include-for-linq-to-sql-and-maybe-other-providers" title="Include for LINQ to SQL (and maybe other providers) ">an interesting extension method</a> that allows you to do eager loading in a persistence ignorant (read: testable) way. You should definitely check it out.</font></font></p><p><font color="#ff0000">UPDATE 2010-12-01: </font><a rel="external" href="http://www.dennisdoomen.net/" title="Weblog Dennis Doomen">Dennis Doomen</a> <a rel="external" href="http://twitter.com/ddoomen/status/4821350065643520" title="Twitter - ddoomen - Refactoring our repositories and its usages in the spirit of this article">used</a> the design described in this article <a rel="external" href="http://twitter.com/ddoomen/status/4883841843986433" title="Twitter - ddoomen - Awesome. We finished redesigning the entire repository/unit-of-work design. Definitely reduced a lot of our technical debt.">successfully</a> in one of his applications. He also used this design in his <a rel="external" href="http://silverlightcookbook.codeplex.com/" title="The Silverlight Cookbook - A Reference Application for Silverlight 4 LOB Apps">Silverlight Cookbook reference architecture</a>. </p>  <h5>Conclusion</h5>  <p>As you know there is not a problem in software design that can&rsquo;t be solved by adding a layer of abstraction, except of course the problem of too many layers of abstraction :-). While this might seem like a lot of code, don&rsquo;t forget that you only need the code for the persistence framework you're using (I included code for both LINQ to SQL as Entity Framework). Also, when you don&rsquo;t need multiple data stores, like I do, the design can be simplified. One of the big plusses for me about this design is the amount of code it saves me to write while writing unit testing.</p>   <p>Cheers</p>
		]]></content>
		<author>
			<name>Steven</name>
		</author>
	</entry>
	
	
	
	<entry>
		<title>Adding Enum Support to Entity Framework LINQ queries</title>
		<link rel="alternate" type="text/html" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=83" />
		<updated>2011-03-19T16:03:00+02:00</updated>
		<published>2010-11-11T11:39:00+02:00</published>
		<id>tag:pivotpowered,2012:NETJunkie.83</id>
		<link rel="related" type="text/html" href=""  />
		<summary type="text">Roger Alsing wrote an interesting post yesterday about adding support for enums to LINQ queries. It is nice to see what Roger is doing  with the .NET 4.0 ExpressionVisitor to change Expression trees that  allow this behavior. What I dislike however, is that for this solution  you need to reimplement all Queryable extension methods. So I thought  about this and found a more pleasant way of intercepting query  calls.</summary>
        <content type="html" xml:lang="en" xml:base="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=83"><![CDATA[
                Roger Alsing wrote an interesting post yesterday about adding support for enums to LINQ queries. It is nice to see what Roger is doing  with the .NET 4.0 ExpressionVisitor to change Expression trees that  allow this behavior. What I dislike however, is that for this solution  you need to reimplement all Queryable extension methods. So I thought  about this and found a more pleasant way of intercepting query  calls.<p>You should definitely start by read <a rel="external" href="http://rogeralsing.com/2010/11/10/entity-framework-4-enum-support-in-linq/" title="Roger Alsing Weblog - Entity Framework 4 Enum support in Linq">Roger's post</a>. What Roger does is creating a new <span class="type">Expression</span> object based on a supplied one. As I said, he abuses extension methods to get this work. It would be nicer if we could just intercept calls to the <span class="type">IQueryProvider</span> and replace expressions before they get executed.</p><p>The trick is to wrap an <span class="type">IQueryable</span><span class="code">&lt;T&gt;</span> and a <span class="type">IQueryProvider</span> object in decorators that allow you to intercept these calls. Then, instead of returning the repositories of your LINQ provider (<span class="type">ObjectQuery</span><span class="code">&lt;T&gt;</span> for Entity Framework and <span class="type">Table</span><span class="code">&lt;T&gt;</span> when using LINQ to SQL) you wrap them in a decorator. Downside of this is that you can't use <span class="type">Table</span><span class="code">&lt;T&gt;</span> or <span class="type">ObjectQuery</span><span class="code">&lt;T&gt;</span> directly in your code. However, I doubt that you really want this. You want your code to be testable and this would lead you to a design such as described in <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=84" title=".NET Junkie - Faking your LINQ provider">this post of mine</a>.<a rel="external" href="http://stackoverflow.com/questions/4128640/how-to-remove-unit-of-work-functionality-from-repositories-using-ioc/4132186#4132186" title="Stackoverflow - How to remove unit of work functionality from repositories using IOC"> </a></p><p>Please note that LINQ to SQL actually <a rel="external" href="http://stackoverflow.com/questions/211875/linq-to-sql-mapping-enum-from-string" title="Stackoverflow - LINQ to SQL Mapping Enum from string">supports</a> Enum values, but still these transformation can be useful to create support for a large range of other interesting features. It would be nice to have a community site were developers can share extensions for rewriting Expression trees to add all sorts of new behavior to LINQ queries. The popularity of snippets could trigger Microsoft to add native support for these features in a next version of Entity Framework and LINQ to SQL.</p><p>I created an <span class="type">InterceptingQueryable</span><span class="code">&lt;T&gt;</span> that you can return in your code. The creation of the repository could look like this:</p><pre class="cs" language="csharp" customtypes="IQueryable Table InterceptingQueryable ExecutingQueryEventArgs Expression ServiceLocator ExpressionTransformer InterceptingQueryProvider IQueryProvider" customvaluetypes="PutYourCustomValueTypesHere">protected override IQueryable&lt;TEntity&gt; GetRepository&lt;TEntity&gt;()<br />    where TEntity : class<br />{<br />    Table&lt;TEntity&gt; table = this.db.GetTable&lt;TEntity&gt;();<br /><br />    var interceptor = new InterceptingQueryable&lt;TEntity&gt;(table);<br /><br />    interceptor.InterceptingProvider.ExecutingQuery +=<br />        TransformExpression;<br /><br />    return interceptor;<br />}<br /><br />void TransformExpression(object sender, ExecutingQueryEventArgs e)<br />{<br />    // replace the expression with a new one<br />    e.Expression = [Use Rogers code here];<br /><br />    // or you could even use a DI fx to get multiple transformations<br />    var transformers = ServiceLocator.Current<br />        .GetAllInstances&lt;ExpressionTransformer&gt;();<br /><br />    foreach (var transformer in transformers)<br />    {<br />        e.Expression = transformer.Transform(e.Expression);<br />    }<br />}<br /></pre><p>Here is the code for the <span class="type">InterceptingQueryable</span><span class="code">&lt;T&gt;</span>:</p><pre class="cs" language="csharp" customtypes="IQueryable Table InterceptingQueryable ExecutingQueryEventArgs Expression ServiceLocator ExpressionTransformer InterceptingQueryProvider IQueryProvider" customvaluetypes="PutYourCustomValueTypesHere">public class InterceptingQueryable&lt;T&gt; : IQueryable&lt;T&gt;<br />{<br />    private readonly IQueryable&lt;T&gt; wrapped;<br />    private InterceptingQueryProvider queryProvider;<br /><br />    public InterceptingQueryable(IQueryable&lt;T&gt; wrapped)<br />    {<br />        this.wrapped = wrapped;<br />    }<br /><br />    public Type ElementType<br />    {<br />        get { return this.wrapped.ElementType; }<br />    }<br /><br />    public Expression Expression<br />    {<br />        get { return this.wrapped.Expression; }<br />    }<br /><br />    public IQueryProvider Provider<br />    {<br />        get { return this.InterceptingProvider; }<br />    }<br /><br />    public IEnumerator&lt;T&gt; GetEnumerator()<br />    {<br />        return this.wrapped.GetEnumerator();<br />    }<br /><br />    IEnumerator IEnumerable.GetEnumerator()<br />    {<br />        return ((IEnumerable)this.wrapped).GetEnumerator();<br />    }<br /><br />    public InterceptingQueryProvider InterceptingProvider<br />    {<br />        get<br />        {<br />            if (this.queryProvider == null)<br />            {<br />                this.queryProvider = new InterceptingQueryProvider(<br />                    this.wrapped.Provider);<br />            }<br /><br />            return this.queryProvider;<br />        }<br />    }<br />}<br /></pre><p>The <span class="type">InterceptingQueryable</span><span class="code">&lt;T&gt;</span> uses a <span class="type">InterceptingQueryProvider</span> that allows you to hook on to:</p><pre class="cs" language="csharp" customtypes="IQueryable Table InterceptingQueryable ExecutingQueryEventArgs Expression ServiceLocator ExpressionTransformer InterceptingQueryProvider IQueryProvider" customvaluetypes="PutYourCustomValueTypesHere">public class ExecutingQueryEventArgs : EventArgs<br />{<br />    public Expression Expression { get; set; }<br />}<br /><br />public class InterceptingQueryProvider : IQueryProvider<br />{<br />    private readonly IQueryProvider wrapped;<br /><br />    public InterceptingQueryProvider(IQueryProvider wrapped)<br />    {<br />        this.wrapped = wrapped;<br />    }<br /><br />    public event EventHandler&lt;ExecutingQueryEventArgs&gt; ExecutingQuery;<br /><br />    public IQueryable&lt;TElement&gt; CreateQuery&lt;TElement&gt;(Expression expression)<br />    {<br />        return this.wrapped.CreateQuery&lt;TElement&gt;(this.Transform(expression));<br />    }<br /><br />    public IQueryable CreateQuery(Expression expression)<br />    {<br />        return this.wrapped.CreateQuery(this.Transform(expression));<br />    }<br /><br />    public TResult Execute&lt;TResult&gt;(Expression expression)<br />    {<br />        return this.wrapped.Execute&lt;TResult&gt;(this.Transform(expression));<br />    }<br /><br />    public object Execute(Expression expression)<br />    {<br />        return this.wrapped.Execute(this.Transform(expression));<br />    }<br /><br />    protected virtual void OnExecutingQuery(ExecutingQueryEventArgs e)<br />    {<br />        if (this.ExecutingQuery != null)<br />        {<br />            this.ExecutingQuery(this, e);<br />        }<br />    }<br /><br />    private Expression Transform(Expression expression)<br />    {<br />        var e = new ExecutingQueryEventArgs() { Expression = expression };<br /><br />        this.OnExecutingQuery(e);<br /><br />        return e.Expression;<br />    }<br />}<br /></pre><p>Cool! Happy querying!</p>
		]]></content>
		<author>
			<name>Steven</name>
		</author>
	</entry>
	
	
	
	<entry>
		<title>Using IDataErrorInfo with Validation Application Block</title>
		<link rel="alternate" type="text/html" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=82" />
		<updated>2012-03-13T21:40:00+02:00</updated>
		<published>2010-10-26T18:08:00+02:00</published>
		<id>tag:pivotpowered,2012:NETJunkie.82</id>
		<link rel="related" type="text/html" href=""  />
		<summary type="text">The IDataErrorInfo interface is a core part of the .NET framework and  both WPF and ASP.NET MVC use this interface for validation purposes. In  this article I will show how to build an abstract base class that  implements IDataErrorInfo in a way that Validation Application Block is  used under the covers.</summary>
        <content type="html" xml:lang="en" xml:base="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=82"><![CDATA[
                The IDataErrorInfo interface is a core part of the .NET framework and  both WPF and ASP.NET MVC use this interface for validation purposes. In  this article I will show how to build an abstract base class that  implements IDataErrorInfo in a way that Validation Application Block is  used under the covers.<p>Using the <span class="type">IDataErrorInfo</span> interface on domain or ViewModel objects is one of the ways to leaverage validation in UI technologies such as WPF and ASP.NET MVC. Having to implement that interface (with its properties) on each and every ViewModel or domain object however, is quite cumbersome and is certainly not <a rel="external" href="http://en.wikipedia.org/wiki/Don%27t_repeat_yourself" title="Wikipedia = Dont repeat yourself">DRY</a>. It is much more convenient to use a base class that implements everything you need. This way, instead of having to implement the complete <span class="type">IDataErrorInfo</span> interface, we can simply inherit from this base class:</p><pre class="cs" language="csharp" customtypes="Customer DataErrorInfo">public partial class Customer : DataErrorInfo<br />{<br />}</pre><p>Below is the code for the <span class="type">DataErrorInfo</span> class. If you look closely you will see a couple of interesting things. First of all, the <span class="type">IDataErrorInfo</span> interface members are implemented explicitly to prevent them from showing up using IntelliSense, because they have no other purpose than for validation by a UI technology. Next, the code uses VAB&rsquo;s <span class="type">PropertyValidationFactory</span> to ensure only the requested property is validated. Not only is this more efficient than validating the complete entity, it also prevents us from having to figure out which errors are caused by that particular property.</p><pre class="cs" language="csharp" customtypes="DataErrorInfo IDataErrorInfo Validator ReflectionMemberValueAccessBuilder PropertyValidationFactory PropertyInfo ValidationFactory DataErrorInfoHelper" customvaluetypes="ValidationSpecificationSource">public abstract class DataErrorInfo : IDataErrorInfo<br />{<br />    string IDataErrorInfo.Error<br />    {<br />        get { return DataErrorInfoHelper.GetErrorInfo(this); }<br />    }<br /><br />    string IDataErrorInfo.this[string columnName]<br />    {<br />        get { return DataErrorInfoHelper.GetErrorInfo(this, columnName); }<br />    }<br />}<br /><br />public static class DataErrorInfoHelper<br />{<br />    public static string GetErrorInfo(object entity)<br />    {<br />        var type = entity.GetType();<br />        var validator =<br />            ValidationFactory.CreateValidator(type);<br />        var results = validator.Validate(entity);<br />        return String.Join(&quot; &quot;, <br />            results.Select(r =&gt; r.Message).ToArray());<br />    }<br />    <br />    public static string GetErrorInfo(object entity,<br />        string propertyName)<br />    {<br />        PropertyInfo property =<br />            entity.GetType().GetProperty(propertyName);<br /><br />        return GetErrorInfo(entity, property);    <br />    }<br /><br />    public static string GetErrorInfo(object entity, <br />        PropertyInfo property)<br />    {<br />        var validator = GetPropertyValidator(entity,<br />            property);<br /><br />        if (validator != null)<br />        {<br />            var results = validator.Validate(entity);<br /><br />            return String.Join(&quot; &quot;, <br />                results.Select(r =&gt; r.Message).ToArray());<br />        }<br /><br />        return string.Empty;<br />    }<br /><br />    private static Validator GetPropertyValidator(<br />        object entity, PropertyInfo property)<br />    {<br />        string ruleset = string.Empty;<br />        var source = ValidationSpecificationSource.All;<br />        var builder = new ReflectionMemberValueAccessBuilder();<br /><br />        return PropertyValidationFactory.GetPropertyValidator(<br />            entity.GetType(), property, ruleset, source, builder);<br />    }<br />}</pre><p>When you are in the unlucky position of using Entity Framework 3.5 (my condolences btw), you are stuck to inheriting your entities from <span class="type">EntityObject</span> or <span class="type">ComplexObject</span>. In that case, you need to define the partial class as follows:</p><pre class="cs" language="csharp" customtypes="Customer IDataErrorInfo DataErrorInfoHelper" customvaluetypes="PutYourCustomValueTypesHere">public partial class Customer : IDataErrorInfo<br />{<br />    string IDataErrorInfo.Error<br />    {<br />        get { return DataErrorInfoHelper.GetErrorInfo(this); }<br />    }<br /><br />    string IDataErrorInfo.this[string columnName]<br />    {<br />        get { return DataErrorInfoHelper.GetErrorInfo(this, columnName); }<br />    }<br />}</pre><p>In other words, you can't inherit from a base type, but must implement <span class="type">IDataErrorInfo</span> directly and implement the interface members in each type. </p><p>Happy validating.</p>
		]]></content>
		<author>
			<name>Steven</name>
		</author>
	</entry>
	
	
	
	<entry>
		<title>Dependency Injection in ASP.NET Web Forms with the Common Service Locator</title>
		<link rel="alternate" type="text/html" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=81" />
		<updated>2012-01-21T01:07:00+02:00</updated>
		<published>2010-10-03T01:25:00+02:00</published>
		<id>tag:pivotpowered,2012:NETJunkie.81</id>
		<link rel="related" type="text/html" href=""  />
		<summary type="text">This article describes how to create and configure a custom PageHandlerFactory class that enables automatic constructor injection for System.Web.UI.Page classes. This keeps your application design clean and allows you to keep the applications dependency to the IoC library to a minimum.</summary>
        <content type="html" xml:lang="en" xml:base="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=81"><![CDATA[
                This article describes how to create and configure a custom PageHandlerFactory class that enables automatic constructor injection for System.Web.UI.Page classes. This keeps your application design clean and allows you to keep the application&rsquo;s dependency to the IoC library to a minimum.<p>When working with <a rel="external" href="http://en.wikipedia.org/wiki/Inversion_of_control" title="Wikipedia - Inversion of control">IoC</a> frameworks, one should always try to minimize the amount of application code that takes a dependency on that framework. In an ideal world, there would only be a single place in the application were the container is queried for dependencies. ASP.NET Web Forms however, was never designed with these concepts in mind. It therefore is tempting to directly request for dependencies in the Page classes instead of looking for a workaround. This is what a Page could look like without such a workaround:</p>  <pre class="cs" language="csharp" customtypes="_Default Page Samurai ServiceLocator">public partial class _Default : System.Web.UI.Page<br />{<br />    private IUserService userService;<br /><br />    public _Default()<br />    {<br />        this.userService = ServiceLocator.Current.GetInstance&lt;IUserService&gt;();<br />    }<br />} </pre>  <p>While this doesn&rsquo;t look that bad, it creates a dependency on an particular implementation and even when your calling an abstraction (as I do with the <a rel="external" href="http://commonservicelocator.codeplex.com" title="Common Service Locator">Common Service Locator</a> in the example) you might want to prevent this, because you&rsquo;ve still got a dependency and a bit of plumbing in each and every page.</p>  <p>The way to intercept the creation of Page types in ASP.NET Web Forms, is by replacing the default <a rel="external" href="http://msdn.microsoft.com/en-us/library/system.web.ui.pagehandlerfactory.aspx" title=".NET Framework Class Library PageHandlerFactory Class"><span class="type">PageHandlerFactory</span></a> implementation. While some think that automatic constructor injection is not possible with Web Forms, I will show you otherwise.</p><p>The code below shows my <span class="type">CommonServiceLocatorPageHandlerFactory</span>. This is a <span class="type">PageHandlerFactory</span> that uses automatic constructor injection to create new <span class="type">Page</span> types by using the Common Service Locator (CSL) interface. I deliberately use the CSL for this, because my <a rel="external" href="http://simpleservicelocator.codeplex.com" title="Simple Service Locator">Simple Service Locator</a> library depends on that interface. If you're not using the CSL, changing the code to work with your IoC library is can be done by changing a single line, as you will see below.</p><p>When using this custom <span class="type">PageHandlerFactory</span> the previously shown Page class can be changed to the following:</p>  <pre class="cs" language="csharp" customtypes="_Default Page Samurai">public partial class _Default : System.Web.UI.Page<br />{<br />    private IUserService userService;<br /><br />    protected _Default()<br />    {<br />    }<br /><br />    public _Default(IUserService userService)<br />    {<br />        this.userService = userService;<br />    }<br />}</pre>   <p>Please note that the page must contain the default constructor. The code compilation model that ASP.NET uses behind the covers, creates a new type based on the defined <span class="type">_Default</span> type. ASP.NET does this to allow the creation of the control hierarchy as it is defined in the markup. Because of this inheriting strategy, every Page class in your application must have a default constructor, although it doesn&rsquo;t have to be public.</p><p>Registration of the <span class="type">CommonServiceLocatorPageHandlerFactory</span> can be done in the web.config in the following way:</p>   <pre class="xml" language="xml">&lt;?xml version=&quot;1.0&quot;?&gt;<br />&lt;configuration&gt;<br />  &lt;system.web&gt;<br />    &lt;httpHandlers&gt;<br />      &lt;add verb=&quot;*&quot; path=&quot;*.aspx&quot;<br />        type=&quot;CSL.CommonServiceLocatorPageHandlerFactory, CSL&quot;/&gt;<br />    &lt;/httpHandlers&gt;<br />  &lt;/system.web&gt;<br />  &lt;system.webServer&gt;<br />    &lt;handlers&gt;<br />      &lt;add name=&quot;CSLPageHandler&quot; verb=&quot;*&quot; path=&quot;*.aspx&quot;<br />        type=&quot;CSL.CommonServiceLocatorPageHandlerFactory, CSL&quot;/&gt;<br />    &lt;/handlers&gt;<br />  &lt;/system.webServer&gt;<br />&lt;/configuration&gt;</pre>   <p>Here is the code for the <span class="type">CommonServiceLocatorPageHandlerFactory</span>:</p>  <pre class="cs" language="csharp" customtypes="UserControl MethodBase Page Control SimpleInjectorPageHandlerFactory  CommonServiceLocatorPageHandlerFactory PageHandlerFactory ServiceLocator IHttpHandler HttpContext ConstructorInfo ActivationException" customvaluetypes="BindingFlags">public class SimpleInjectorPageHandlerFactory <br />    : PageHandlerFactory<br />{<br />    private static object GetInstance(Type type)<br />    {<br />        // Change this line if you're not using the CSL,<br />        // but a DI framework directly.<br />        return Microsoft.Practices.ServiceLocation<br />            .ServiceLocator.Current.GetInstance(type);<br />    }<br /><br />    public override IHttpHandler GetHandler(HttpContext context,<br />        string requestType, string virtualPath, string path)<br />    {<br />        var handler = base.GetHandler(context, requestType, <br />            virtualPath, path);<br /><br />        if (handler != null)<br />        {<br />            InitializeInstance(handler);<br />            HookChildControlInitialization(handler);<br />        }<br /><br />        return handler;<br />    }<br /><br />    private void HookChildControlInitialization(object handler)<br />    {<br />        Page page = handler as Page;<br /><br />        if (page != null)<br />        {<br />            // Child controls are not created at this point.<br />            // They will be when PreInit fires.<br />            page.PreInit += (s, e) =&gt;<br />            {<br />                InitializeChildControls(page);<br />            };<br />        }<br />    }<br /><br />    private static void InitializeChildControls(Control contrl)<br />    {<br />        var childControls = GetChildControls(contrl);<br /><br />        foreach (var childControl in childControls)<br />        {<br />            InitializeInstance(childControl);<br />            InitializeChildControls(childControl);<br />        }<br />    }<br /><br />    private static Control[] GetChildControls(Control ctrl)<br />    {<br />        var flags =<br />            BindingFlags.Instance | BindingFlags.NonPublic;<br /><br />        return (<br />            from field in ctrl.GetType().GetFields(flags)<br />            let type = field.FieldType<br />            where typeof(UserControl).IsAssignableFrom(type)<br />            let userControl = field.GetValue(ctrl) as Control<br />            where userControl != null<br />            select userControl).ToArray();<br />    }<br /><br />    private static void InitializeInstance(object instance)<br />    {<br />        Type pageType = instance.GetType().BaseType;<br /><br />        var ctor = GetInjectableConstructor(pageType);<br /><br />        if (ctor != null)<br />        {<br />            try<br />            {<br />                var args = GetMethodArguments(ctor);<br /><br />                ctor.Invoke(instance, args);<br />            }<br />            catch (Exception ex)<br />            {<br />                var msg = string.Format(&quot;The type {0} &quot; +<br />                    &quot;could not be initialized. {1}&quot;, pageType,<br />                    ex.Message);<br /><br />                throw new InvalidOperationException(msg, ex);<br />            }<br />        }<br />    }<br /><br />    private static ConstructorInfo GetInjectableConstructor(<br />        Type type)<br />    {<br />        var overloadedPublicConstructors = (<br />            from ctor in type.GetConstructors()<br />            where ctor.GetParameters().Length &gt; 0<br />            select ctor).ToArray();<br /><br />        if (overloadedPublicConstructors.Length == 0)<br />        {<br />            return null;<br />        }<br /><br />        if (overloadedPublicConstructors.Length == 1)<br />        {<br />            return overloadedPublicConstructors[0];<br />        }<br /><br />        throw new ActivationException(string.Format(<br />            &quot;The type {0} has multiple public overloaded &quot; +<br />            &quot;constructors and can't be initialized.&quot;, type));<br />    }<br /><br />    private static object[] GetMethodArguments(MethodBase method)<br />    {<br />        return (<br />            from parameter in method.GetParameters()<br />            let parameterType = parameter.ParameterType<br />            select GetInstance(parameterType)).ToArray();<br />    }<br />}</pre>  <p>This implementation does one sneaky thing to achieve it&rsquo;s goal. It is nearly impossible to instantiate the type our self, because that would mean that we need to rewrite the complete compilation engine of ASP.NET. Instead we delegate the creation to the <span class="type">PageHandlerFactory</span> base class. After the creation of this type (created using the default constructor) we search for an overloaded constructor on its base type (remember that ASP.NET creates a sub type), find out what arguments this constructor has, and load those dependencies by calling the Common Service Locator. After that we invoke that overloaded constructor. I repeat: <em>we call an overloaded constructor on an <u>already initialized</u> class</em>.</p>  <p>This is very sneaky, but works like hell. Besides initializing the <span class="type">Page</span> class itself, it will initializes all <span class="type">UserControl</span>s recursively.</p><p>A few side notes: Keep in mind that this <u>will</u> fail in partially trusted environments. When doing this in partial trust, there is no good feasible workaround. In partial trust there is not much else we can do than seeing the <span class="type">Page</span> as a <strong>Composition Root</strong> and calling the container from within the default constructor. Second note: This will only work for .aspx pages. For intercepting the creation of .ashx HTTP Handlers we will need to create a custom <span class="type">IHttpHandlerFactory</span>, which is new since ASP.NET 2.0. </p>  <p>Happy injecting!</p>
		]]></content>
		<author>
			<name>Steven</name>
		</author>
	</entry>
	
	
	
	<entry>
		<title>Mixing Validation Application Block With DataAnnotation: What About SelfValidation?</title>
		<link rel="alternate" type="text/html" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=80" />
		<updated>2011-12-04T12:48:00+02:00</updated>
		<published>2010-09-12T20:24:00+02:00</published>
		<id>tag:pivotpowered,2012:NETJunkie.80</id>
		<link rel="related" type="text/html" href=""  />
		<summary type="text">This article describes how to move the self validation methods of a type to its meta data type, using Validation Application Block 5.0. Using self validation methods inside Data Annotations' meta data type is something that is not supported out of the box.</summary>
        <content type="html" xml:lang="en" xml:base="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=80"><![CDATA[
                This article describes how to move the self validation methods of a type to its meta data type, using Validation Application Block 5.0. Using self validation methods inside Data Annotations' meta data type is something that is not supported out of the box.<p>The newest version of the Validation Application Block, version 5.0, now integrates with .NET Data Annotations (new since .NET 3.5 sp1). Data Annotations is a general model for annotating data using attributes, which is especially useful for validation. Attribute based validation is of course one of the options when doing validation using the Validation Application Block.</p><p>One of the nice things about Data Annotations is that it contains a feature called 'buddy classes', which allows you to put the validation attributes in a separate class that will function as meta data type. This is especially useful when dealing with auto-generated classes (think LINQ to SQL, Entity Framework). Validation Application Block 5.0 is now able to use this annotation model and we're therefore now able to do something like this with VAB:</p> <pre class="cs" language="csharp" customtypes="MetadataType PersonMetaData Person NotNullValidator" customvaluetypes="PutYourCustomValueTypesHere">// DataAnnotations Metadata attribute<br />[MetadataType(typeof(PersonMetaData))]<br />public partial class Person<br />{<br />    public string Name { get; set; }<br />}<br /> <br />public class PersonMetaData<br />{<br />    // VAB validation attribute<br />    [NotNullValidator]<br />    public string Name { get; set; }<br />}</pre>  <p>This works great, but what about self validation? VAB allows methods to be placed on objects that allow custom validation logic that can't be written as custom attributes. How do we move this logic to the <span class="type">PersonMetaData</span> class?</p><p>The short answer is: you can't. VAB does not support this out of the box. However, for those of you who follow this series about the VAB, you already know by now that there is little that can't be done with the VAB with a bit of work.</p><p>Please note that I think that having such feature is probably only useful in a narrow range of scenarios, because self validation method can located in a partial class. For the sake of education and having fun with VAB, let's just do this anyway ;-) </p><p>This can be achieved by hooking into the framework using depedency injection and replace the existing <span class="type">AttributeValidationFactory</span> implementation. Below is a complete working example of how to do this with VAB 5.0 in three 'simple' steps:</p><ol><li>Change the signature of your validation methods.</li><li>Define a class that can replace the VAB's build-in <span class="type">AttributeValidationFactory</span>.</li><li>Reconfigure VAB in the start up path of your application.</li></ol><h4>1. Change the signature of your validation methods.</h4><p>Because self validation methods are instance methods they are able to validate instance fields on the validated type. When you move the validation method to the meta data type you loose this ability. So for this to work we'll have to change the signature of the validation method to at least contain the object to validate as method argument. When we make this validation method static we can prevent a new instance of the meta data type from being created during the validation process. Here is an example of a type that has its self validation moved to its meta data type:</p><pre class="cs" language="csharp" customtypes="MetadataType PersonMetaData Person NotNullValidator SelfValidation ValidationResults">[MetadataType(typeof(PersonMetaData))]<br />public class Person<br />{<br />    public string Name { get; set; }<br />}<br /><br />public class PersonMetaData<br />{<br />    [NotNullValidator]<br />    public string Name { get; set; }<br /><br />    [SelfValidation]<br />    public static void SelfValidator(Person instance,<br />        ValidationResults results)<br />    {<br />        // TODO: Your validation here.<br />    }<br />}</pre><h4>2. Define a class that can replace the VAB's build in AttributeValidatorFactory.</h4><p>When using attribute based validation, the <span class="type">AttributeValidationFactory</span> type, that lives in the <span class="code">Microsoft.Practices.EnterpriseLibrary.Validation</span> namespace, is responsible for creating new validators based on the attributes you decorated. When we replace it with an extended implementation that is able to handle self validations on the meta data class. Here is my <span class="type">ExtendedAttributeValidationFactory</span> implementation: </p><pre class="cs" language="csharp" customtypes="ExtendedAttributeValidationFactory AttributeValidatorFactory IValidationInstrumentationProvider Validator ValidatorFactory AndCompositeValidator MetadataTypeAttribute ValidationResults ValidationReflectionHelper SelfValidationAttribute MetaDataSelfValidationValidator" customvaluetypes="BindingFlags">public class ExtendedAttributeValidationFactory :<br />    AttributeValidatorFactory<br />{<br />    public ExtendedAttributeValidationFactory(<br />        IValidationInstrumentationProvider provider)<br />        : base(provider)<br />    {<br />    }<br /><br />    protected override Validator InnerCreateValidator(<br />        Type targetType, string ruleset,<br />        ValidatorFactory mainValidatorFactory)<br />    {<br />        var baseValidator = base.InnerCreateValidator(<br />            targetType, ruleset, mainValidatorFactory);<br /><br />        var metaDataValidator =<br />            CreateValidatorForMetaDataSelfValidation(<br />                targetType, ruleset);<br /><br />        if (metaDataValidator == null)<br />        {<br />            return baseValidator;<br />        }<br /><br />        return new AndCompositeValidator(baseValidator,<br />            metaDataValidator);<br />    }<br /><br />    private Validator CreateValidatorForMetaDataSelfValidation(<br />        Type targetType, string ruleset)<br />    {<br />        var attributes = GetMetadataTypes(targetType).ToArray();<br /><br />        if (attributes.Length == 0)<br />            return null;<br /><br />        var flags = BindingFlags.Public |<br />            BindingFlags.NonPublic | BindingFlags.Static;<br /><br />        var selfValidators = (<br />            from attribute in attributes<br />            from method in attribute.MetadataClassType.GetMethods(flags)<br />            where method.ReturnType == typeof(void)<br />            let parameters = method.GetParameters()<br />            where parameters.Length == 2<br />            where parameters[1].ParameterType == typeof(ValidationResults)<br />            from methodAtrtibute in<br />                ValidationReflectionHelper.GetCustomAttributes(method,<br />                    typeof(SelfValidationAttribute), false)<br />                .Cast&lt;SelfValidationAttribute&gt;()<br />            where ruleset.Equals(methodAtrtibute.Ruleset)<br />            select new MetaDataSelfValidationValidator(method)).ToArray();<br /><br />        if (selfValidators.Length == 0)<br />            return null;<br /><br />        return new AndCompositeValidator(selfValidators);<br />    }<br /><br />    private static IEnumerable&lt;MetadataTypeAttribute&gt; GetMetadataTypes(<br />        Type targetType)<br />    {<br />        while (targetType != null)<br />        {<br />            var metadata = targetType.GetCustomAttributes(<br />                typeof(MetadataTypeAttribute), false)<br />                .FirstOrDefault();<br /><br />            if (metadata != null)<br />            {<br />                yield return (MetadataTypeAttribute)metadata;<br />            }<br /><br />            targetType = targetType.BaseType;<br />        }<br />    }<br />}<br /></pre><p>The <span class="type">ExtendedAttributeValidationFactory</span> class loops through all static methods of the meta data class and foreach method that follows the conventions and is of the correct ruleset, a new <span class="type">MetaDataSelfValidationValidator</span> is created. These are the conventions a validation method must follow:</p><ul><li>The method must be static.</li><li>The method must return void.</li><li>The method must contain two arguments.</li><li>The first argument must be of the validated type or a base type.</li><li>The second argument must be of type <span class="type">ValidationResults</span>.</li><li>The method must be decorated with the <span class="code">[</span><span class="type">SelfValidationAttribute</span><span class="code">]</span>.</li></ul><p>The <span class="type">MetaDataSelfValidationValidator</span> class enables validation of an object by calling the static self validation method of the meta data type. Here's the code:</p><pre class="cs" language="csharp" customtypes="MetaDataSelfValidationValidator Validator MethodInfo ValidationResults">public class MetaDataSelfValidationValidator : Validator<br />{<br />    private readonly MethodInfo methodInfo;<br /><br />    public MetaDataSelfValidationValidator(MethodInfo methodInfo) <br />        : base(null, null)<br />    {<br />        this.methodInfo = methodInfo;<br />    }<br /><br />    public override void DoValidate(object objectToValidate, <br />        object currentTarget, string key, <br />        ValidationResults validationResults)<br />    {<br />        if (objectToValidate != null)<br />        {<br />            this.methodInfo.Invoke(null, <br />                new object[] { objectToValidate, validationResults });<br />        }<br />    }<br /><br />    protected override string DefaultMessageTemplate<br />    {<br />        get { return null; }<br />    }<br />}<br /></pre><h4>3. Reconfigure VAB in the start up path of your application.</h4><p>Now we've written a new implementation of the <span class="type">AttributeValidationFactory</span>, we will have to replace the current implementation with this new one. We can do this by reconfiguring the Unity container (the standard IoC framework for EntLib) to return a new instance of the <span class="type">ExtendedAttributeValidationFactory</span> type when an <span class="type">AttributeValidationFactory</span> is requested by VAB:</p><pre class="cs" language="csharp" customtypes="IConfigurationSource UnityContainer UnityContainerConfigurator AttributeValidatorFactory ExtendedAttributeValidationFactory IServiceLocator UnityServiceLocator EnterpriseLibraryContainer">// Create the container<br />var container = new UnityContainer();<br /><br />// Configurator will read Enterprise Library <br />// configuration and set up the container<br />var configurator = new UnityContainerConfigurator(container);<br /><br />IConfigurationSource configurationSource = <br />    new NullConfigurationSource();<br />EnterpriseLibraryContainer.ConfigureContainer(<br />    configurator, configurationSource);<br /><br />container.RegisterType&lt;AttributeValidatorFactory, <br />    ExtendedAttributeValidationFactory&gt;();<br /><br />// Wrap in ServiceLocator<br />IServiceLocator locator = new UnityServiceLocator(container);<br /><br />// And set Enterprise Library to use it<br />EnterpriseLibraryContainer.Current = locator;<br /></pre><p>Happy self validating ;-)</p>
		]]></content>
		<author>
			<name>Steven</name>
		</author>
	</entry>
	
	
	
	<entry>
		<title>Integrating Validation Application Block with ASP.NET part 2</title>
		<link rel="alternate" type="text/html" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=79" />
		<updated>2011-08-01T21:17:00+02:00</updated>
		<published>2010-08-28T00:49:00+02:00</published>
		<id>tag:pivotpowered,2012:NETJunkie.79</id>
		<link rel="related" type="text/html" href=""  />
		<summary type="text">This post describes how to take integration of Validation Application Block with ASP.NET Web Forms to the next level by introducing extension methods that centralize the creation of PropertyProxyValidator controls and enable compile time support. This post build on the code in the previous article and allows users to define value conversions.</summary>
        <content type="html" xml:lang="en" xml:base="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=79"><![CDATA[
                This post describes how to take integration of Validation Application Block with ASP.NET Web Forms to the next level by introducing extension methods that centralize the creation of PropertyProxyValidator controls and enable compile time support. This post build on the code in the previous article and allows users to define value conversions.<p>The code I presented in my <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=78" title="Integrating Validation Application Block with ASP.NET part 1">previous post</a> took integration between the <a rel="external" href="http://msdn.microsoft.com/en-us/library/ff664356%28PandP.50%29.aspx" title="Microsoft Enterprise Library 5.0 - The Validation Application Block">Enterprise Library Validation Application Block</a> and ASP.NET WebForms to the next level. There is one short come to this solution that you will soon notice; the <a rel="external" href="http://msdn.microsoft.com/en-us/library/ff664564%28PandP.50%29.aspx" title="PropertyProxyValidator">PropertyProxyValidator</a> throws an exception when trying to validate anything else than plain text. This is a problem the designers of VAB tried to solve. What they came up with was the <span class="code">ValueConvert</span> event on the <span class="type">PropertyProxyValidator</span>. When hooked to the <span class="type">PropertyProxyValidator</span>, the validator will route conversion of values to that event.</p><p>While this mechanism works fine, it has the same problem as I tried to solve in my previous article; It takes a lot of code to hook up, as you can see in <a rel="external" href="http://msdn.microsoft.com/en-us/library/ff664564%28PandP.50%29.aspx" title="Enterprise Library - Integrating with ASP.NET ">this example</a>.</p><p>I like to have an API were I can easily supply a conversion method and optionally supply an error message that should be displayed when the conversion fails. To be able to do this in a compile time friendly way, we need to alter the old API. The old API is used like this:</p><pre class="cs" language="csharp" customtypes="Person" customvaluetypes="PutYourCustomValueTypesHere">this.LastNameTextBox.AddValidatorFor&lt;Person&gt;(p =&gt; p.LastName);</pre><p>Now we want to allow a convertion method to be specified like this:</p><pre class="cs" language="csharp" customtypes="Person" customvaluetypes="PutYourCustomValueTypesHere">this.LastNameTextBox<br />    .AddValidatorFor&lt;Person&gt;(p =&gt; p.Age, Int32.Parse);</pre><p>This however, will not work, because of limitations of the C# compiler. We would have to rewrite the previous example as follows:</p><pre class="cs" language="csharp" customtypes="Person" customvaluetypes="PutYourCustomValueTypesHere">this.LastNameTextBox<br />    .AddValidatorFor&lt;Person, int&gt;(p =&gt; p.Age, Int32.Parse);</pre><p>While this isn't bad, I don't like that I have to specify the int, because the compiler should be able to infer it. We will have to come up with another design that allows this type to be inferred. Here is an example of something that will work:</p><pre class="cs" language="csharp" customtypes="Person">this.LastNameTextBox.For&lt;Person&gt;()<br />    .AddValidator(p =&gt; p.Age, Int32.Parse);</pre><p>Let's cut to the chase. Here is the new implementation:</p><pre class="cs" language="csharp" customtypes="AspNetValidationIntegration AspNetValidationIntegrator BaseValidator Expression Control PropertyProxyValidator LambdaExpression MemberExpression UnaryExpression HttpException" customvaluetypes="ValidatorDisplay">public static class AspNetValidationIntegration<br />{<br />    public static AspNetValidationIntegrator&lt;TEntity&gt; <br />        For&lt;TEntity&gt;(this Control controlToValidate)<br />    {<br />        return new AspNetValidationIntegrator&lt;TEntity&gt;(<br />            controlToValidate);<br />    }<br />}<br /><br />public sealed class AspNetValidationIntegrator&lt;TEntity&gt;<br />{<br />    private readonly Control control;<br /><br />    public AspNetValidationIntegrator(Control control)<br />    {<br />        this.control = control;<br />    }<br /><br />    public BaseValidator AddValidator&lt;TValue&gt;(<br />        Expression&lt;Func&lt;TEntity, TValue&gt;&gt; propertySelector)<br />    {<br />        return this.AddValidator(propertySelector, <br />            string.Empty, null, null);<br />    }<br /><br />    public BaseValidator AddValidator&lt;TValue&gt;(<br />        Expression&lt;Func&lt;TEntity, TValue&gt;&gt; propertySelector, <br />        Func&lt;string, TValue&gt; converter)<br />    {<br />        return this.AddValidator(propertySelector, <br />            string.Empty, converter, null);<br />    }<br /><br />    public BaseValidator AddValidator&lt;TValue&gt;(<br />        Expression&lt;Func&lt;TEntity, TValue&gt;&gt; propertySelector,<br />        Func&lt;string, TValue&gt; converter, <br />        string convertionErrorMessage)<br />    {<br />        return this.AddValidator(propertySelector, <br />            string.Empty, converter, convertionErrorMessage);<br />    }<br /><br />    public BaseValidator AddValidator&lt;TValue&gt;(<br />        Expression&lt;Func&lt;TEntity, TValue&gt;&gt; propertySelector, <br />        string rulesetName)<br />    {<br />        return this.AddValidator(propertySelector, <br />            rulesetName, null, null);<br />    }<br /><br />    public BaseValidator AddValidator&lt;TValue&gt;(<br />        Expression&lt;Func&lt;TEntity, TValue&gt;&gt; propertySelector,<br />        string rulesetName, Func&lt;string, TValue&gt; converter)<br />    {<br />        return this.AddValidator(propertySelector, <br />            rulesetName, converter, null);<br />    }<br /><br />    public BaseValidator AddValidator&lt;TValue&gt;(<br />        Expression&lt;Func&lt;TEntity, TValue&gt;&gt; propertySelector,<br />        string rulesetName, Func&lt;string, TValue&gt; converter, <br />        string convertionErrorMessage)<br />    {<br />        var validator = this.CreateValidator(propertySelector, <br />            rulesetName, converter, convertionErrorMessage);<br /><br />        this.AddValidatorToPageJustAfterControl(validator);<br /><br />        return validator;<br />    }<br /><br />    public BaseValidator CreateValidator&lt;TValue&gt;(<br />        Expression&lt;Func&lt;TEntity, TValue&gt;&gt; propertySelector)<br />    {<br />        return this.CreateValidator(propertySelector, <br />            string.Empty, null, null);<br />    }<br /><br />    public BaseValidator CreateValidator&lt;TValue&gt;(<br />        Expression&lt;Func&lt;TEntity, TValue&gt;&gt; propertySelector, <br />        Func&lt;string, TValue&gt; converter)<br />    {<br />        return this.CreateValidator(propertySelector, <br />            string.Empty, converter, null);<br />    }<br /><br />    public BaseValidator CreateValidator&lt;TValue&gt;(<br />        Expression&lt;Func&lt;TEntity, TValue&gt;&gt; propertySelector,<br />        Func&lt;string, TValue&gt; converter, <br />        string convertionErrorMessage)<br />    {<br />        return this.CreateValidator(propertySelector, <br />            string.Empty, converter, convertionErrorMessage);<br />    }<br /><br />    public BaseValidator CreateValidator&lt;TValue&gt;(<br />        Expression&lt;Func&lt;TEntity, TValue&gt;&gt; propertySelector, <br />        string rulesetName)<br />    {<br />        return this.CreateValidator(propertySelector, <br />            rulesetName, null, null);<br />    }<br /><br />    public BaseValidator CreateValidator&lt;TValue&gt;(<br />        Expression&lt;Func&lt;TEntity, TValue&gt;&gt; propertySelector, <br />        string rulesetName, Func&lt;string, TValue&gt; converter, <br />        string convertionErrorMessage)<br />    {<br />        PropertyProxyValidator proxy = <br />            CreateNewProxyValidator();<br /><br />        proxy.ControlToValidate = this.control.ID;<br /><br />        BindProxyValidatorToDomainProperty(proxy, <br />            propertySelector, rulesetName);<br /><br />        AddConverter(proxy, converter, convertionErrorMessage);<br /><br />        return proxy;<br />    }<br /><br />    private static void AddConverter&lt;TValue&gt;(<br />        PropertyProxyValidator proxy, <br />        Func&lt;string, TValue&gt; converter, string errorMessage)<br />    {<br />        if (converter != null)<br />        {<br />            proxy.ValueConvert += (sender, e) =&gt;<br />            {<br />                string value = e.ValueToConvert as string;<br />                try<br />                {<br />                    e.ConvertedValue = converter(value);<br />                }<br />                catch (Exception ex)<br />                {<br />                    if (string.IsNullOrEmpty(errorMessage))<br />                    {<br />                        e.ConversionErrorMessage = ex.Message;<br />                    }<br />                    else<br />                    {<br />                        e.ConversionErrorMessage = errorMessage;<br />                    }<br />                    <br />                    e.ConvertedValue = null;<br />                }<br />            };<br />        }<br />    }<br /><br />    private static void BindProxyValidatorToDomainProperty&lt;TValue&gt;(<br />        PropertyProxyValidator proxy,<br />        Expression&lt;Func&lt;TEntity, TValue&gt;&gt; propertySelector, <br />        string rulesetName)<br />    {<br />        proxy.PropertyName = GetPropertyName(propertySelector);<br />        proxy.SourceTypeName = typeof(TEntity).AssemblyQualifiedName;<br />        proxy.RulesetName = rulesetName;<br />    }<br /><br />    private void AddValidatorToPageJustAfterControl(<br />        BaseValidator validator)<br />    {<br />        int index = <br />            this.control.Parent.Controls.IndexOf(this.control);<br />        <br />        try<br />        {<br />            this.control.Parent.Controls.AddAt(index + 1, validator);<br />        }<br />        catch (HttpException ex)<br />        {<br />            throw BuildMoreExpressiveException(control, ex);<br />        }<br />    }<br /><br />    private static string GetPropertyName(<br />        LambdaExpression propertySelector)<br />    {<br />        var body = propertySelector.Body;<br /><br />        var member = body as MemberExpression ?? <br />            ((MemberExpression)((UnaryExpression)body).Operand);<br /><br />        return member.Member.Name;<br />    }<br /><br />    private static PropertyProxyValidator CreateNewProxyValidator()<br />    {<br />        var proxy = new PropertyProxyValidator()<br />        {<br />            Display = ValidatorDisplay.Static,<br />        };<br /><br />        // Let's make the proxy more fancy :-)<br />        proxy.Text = &quot;&lt;img src='http://www.cuttingedge.itstatus_failed_small.gif' /&gt;&quot;;<br />        proxy.PreRender += (s, e) =&gt;<br />        {<br />            proxy.Attributes[&quot;title&quot;] =<br />                ReformatErrorMessageForTitle(proxy.ErrorMessage);<br />        };<br /><br />        return proxy;<br />    }<br /><br />    private static string ReformatErrorMessageForTitle(<br />        string errorMessage)<br />    {<br />        errorMessage = errorMessage.Replace(&quot;&lt;br/&gt;&quot;, &quot;,&quot;);<br /><br />        // Remove the last ',', if any.<br />        if (errorMessage.Length &gt; 0 &amp;&amp;<br />            errorMessage[errorMessage.Length - 1] == ',')<br />        {<br />            return errorMessage.Substring(0, errorMessage.Length - 1);<br />        }<br /><br />        return errorMessage;<br />    }<br /><br />    private static Exception BuildMoreExpressiveException(<br />        Control control, HttpException exception)<br />    {<br />        return new InvalidOperationException(string.Format(<br />            &quot;Sorry, you have encountered a rare .NET bug. &quot; +<br />            &quot;Control '{1}', which is the parent control of &quot; + <br />            &quot;'{0}', contains '&lt;% %&gt;' tags. Because of the &quot; + <br />            &quot;existance of those tags, this parent control &quot; + <br />            &quot;can not be modified and it is impossible to &quot; + <br />            &quot;dynamically add validators to it. You can &quot; + <br />            &quot;fix this by wrapping '{0}' in another control&quot; + <br />            &quot;. For instance: &quot; + <br />            &quot;&lt;asp:{2} runat='server' ID='{1}'&gt;&quot; +<br />                &quot;&lt;asp:PlaceHolder runat='server'&gt;&quot; + <br />                    &quot;&lt;asp:{3} runat='server' id='{0}' /&gt;&quot; + <br />                &quot;&lt;/asp:PlaceHolder&gt;&quot; +<br />            &quot;&lt;/asp:{2}&gt;. {4}&quot;, control.ID, control.Parent.ID, <br />            control.Parent.GetType().Name, <br />            control.GetType().Name, exception.Message));<br />    }<br />}</pre><p>The trick here is that the <span class="type">AspNetValidationIntegration</span> class now only has one single extension method named <span class="code">For&lt;TEntity&gt;</span> which will return a new <span class="type">AspNetValidationIntegrator</span><span class="code">&lt;TEntity&gt;</span>. The magic happens in the <span class="code">AddConverter</span> method. In this method the <span class="type">PropertyProxyValidator</span>'s <span class="code">ValueConvert</span> event is hooked. Here is that method again:</p><pre class="cs" language="csharp" customtypes="PropertyProxyValidator" customvaluetypes="PutYourCustomValueTypesHere">     private static void AddConverter&lt;TValue&gt;(<br />        PropertyProxyValidator proxy, <br />        Func&lt;string, TValue&gt; converter, string errorMessage)<br />    {<br />        if (converter != null)<br />        {<br />            proxy.ValueConvert += (sender, e) =&gt;<br />            {<br />                string value = e.ValueToConvert as string;<br />                try<br />                {<br />                    e.ConvertedValue = converter(value);<br />                }<br />                catch (Exception ex)<br />                {<br />                    if (string.IsNullOrEmpty(errorMessage))<br />                    {<br />                        e.ConversionErrorMessage = ex.Message;<br />                    }<br />                    else<br />                    {<br />                        e.ConversionErrorMessage = errorMessage;<br />                    }<br /><br />                    e.ConvertedValue = null;<br />                }<br />            };<br />        }<br />    }</pre><p>The <span class="code">AddConverter</span> method hooks an anonymous method to the <span class="code">ValueConvert</span> event. The <span class="code">converter</span> and <span class="code">errorMessage</span> arguments are used as closures in this anonymous methods and used to do the actual convertion and display an message when the conversion fails.</p><p>Just as before this code hides the use of the <span class="type">PropertyProxyValidator</span> and even the use of the Validation Application block from the presentation layer. Validation Application Block is now just an implementation detail, which, from an architectural perspective, is a good thing.</p><p>Happy validating!</p>
		]]></content>
		<author>
			<name>Steven</name>
		</author>
	</entry>
	
	
	
	<entry>
		<title>Integrating Validation Application Block with ASP.NET part 1</title>
		<link rel="alternate" type="text/html" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=78" />
		<updated>2011-08-01T21:06:00+02:00</updated>
		<published>2010-08-15T15:51:00+02:00</published>
		<id>tag:pivotpowered,2012:NETJunkie.78</id>
		<link rel="related" type="text/html" href=""  />
		<summary type="text">This post describes how to take integration of Validation Application Block with  ASP.NET Web Forms to the next level by introducing extension methods  that centralize the creation of PropertyProxyValidator controls and  enable compile time support.</summary>
        <content type="html" xml:lang="en" xml:base="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=78"><![CDATA[
                This post describes how to take integration of Validation Application Block with  ASP.NET Web Forms to the next level by introducing extension methods  that centralize the creation of PropertyProxyValidator controls and  enable compile time support.<p>Last year, when reading the <a rel="external" href="http://www.microsoft.com/downloads/details.aspx?FamilyID=4f8cd377-5522-4f45-a024-44a6ca5111ec&amp;displaylang=en" title="Hands-On Labs for Microsoft Enterprise Library 5.0">Hands-On Labs</a> <a rel="external" href="http://www.cuttingedge.it/blogs/steven/images/ValidationHOL.zip" title="Hands-On Lab Validation Application Block 4.1">document</a> for the <a rel="external" href="http://msdn.microsoft.com/en-us/library/ff664356%28PandP.50%29.aspx" title="Microsoft Enterprise Library 5.0 The Validation Application Block">Enterprise Library Validation Application Block</a>, it struck me that the integration with ASP.NET Web Forms pretty sucked when using Validation Application Block (VAB). While the Hands-On Labs document has a special chapter (Lab 12) devoted on ASP.NET integration and the framework contains an assembly specially for this task, I couldn&rsquo;t help noticing that it was cumbersome and error prone.</p><p>I have to admit, the Patterns &amp; Practices team did a good job in creating nice design time support. When you follow the instructions in the Hands-On Lab document you will be able to drag a <span class="type">PropertyProxyValidator</span> to the form and configure it. A <a rel="external" href="http://msdn.microsoft.com/en-us/library/ff664564%28PandP.50%29.aspx" title="Integrating with ASP.NET">PropertyProxyValidator</a> is a ASP.NET validator control that functions as proxy between the ASP.NET validation mechanism and the VAB. As its name describes, it allows you to validate a single property from your domain.</p><p>The problem however is that you will usually have many <span class="type">PropertyProxyValidator</span> controls on the page. Each validator has to be configured with at least the type to validate (<span class="code">SourceTypeName</span>),  the name of the property to validate (<span class="code">PropertyName</span>), the ID of the control to validate (<span class="code">ControlToValidate</span>), and optionally the ruleset to validate (<span class="code">RulesetName</span>). Not only is it lot of work to hook up all validators on the page, but the complete configuration is given in markup, making it almost impossible to quickly refactor the domain or the representation of the validators later on.</p><p>Here is an example of how a PropertyProxyValidator looks in markup:</p><pre class="xml" language="xml" customtypes="PutYourCustomTypesHere" customvaluetypes="PutYourCustomValueTypesHere"><font color="#0000ff">&lt;asp:<font color="#800000">TextBox </font><font color="#ff0000">runat</font>=&quot;server&quot; <font color="#ff0000">ID</font>=&quot;FirstNameTextBox&quot; /&gt;<br /><br />&lt;<font color="#800000">vab</font>:<font color="#800000">PropertyProxyValidator </font><font color="#ff0000">runat</font>=&quot;server&quot;<br />    <font color="#ff0000">ID</font>=&quot;Validator1&quot;<br />    <font color="#ff0000">SourceTypeName</font>=&quot;Company.Application.Domain.Person&quot;<br />    <font color="#ff0000">PropertyName</font>=&quot;FirstName&quot;<br />    <font color="#ff0000">ControlToValidate</font>=&quot;FirstNameTextBox&quot;<br />    <font color="#ff0000">RulesetName</font>=&quot;Alternative&quot;<br />/&gt;</font></pre><p>A better solution would be to wire up the validators in the code behind, in a way that gives us compile time support. There is no easy way to do this with VAB out of the box, but as always, it&rsquo;s not difficult to get a pleasurable workaround for this. We could for instance write an extension method that allows appending a validator to the page just behind the control to validate:</p><pre class="cs" language="csharp" customtypes="Person" customvaluetypes="PutYourCustomValueTypesHere">protected override void OnPreInit(EventArgs e)<br />{<br />    // Add a validator for the Person.LastName property.<br />    this.LastNameTextBox.AddValidatorFor&lt;Person&gt;(p =&gt; p.LastName);<br /><br />    // Add a validator for the 'Alternative' VAB ruleset and set <br />    // an alternative ASP.NET validation group.<br />    this.FirstNameTextBox<br />        .AddValidatorFor&lt;Person&gt;(p =&gt; p.FirstName, &quot;Alternative&quot;)<br />        .ValidationGroup = &quot;AlternativeValidationGroup&quot;;<br /><br />    base.OnPreInit(e);<br />}</pre><p>The first line of code registers a validator on the <span class="code">LastNameTextBox</span> for the <span class="type">Person</span><span class="code">.LastName</span> property. The validator will be added to the page directly after the control to validate. The second line registers a validator for the &lsquo;Alternative&rsquo; rule set of the <span class="type">Person</span><span class="code">.FirstName</span>. Because the extension method returns the created validator, we can directly set the <span class="code">ValidationGroup</span> of this validator. Of course I wouldn&rsquo;t advice using literal strings as done in this example, but you get the idea.<br /><br />Here&rsquo;s the code for these extension methods:</p><pre class="cs" language="csharp" customtypes="PropertyProxyValidator BaseValidator Control Expression UnaryExpression MemberExpression HttpException" customvaluetypes="ValidatorDisplay">public static BaseValidator AddValidatorFor&lt;T&gt;(<br />    this Control control, Expression&lt;Func&lt;T, object&gt;&gt; property)<br />{<br />    return AddValidatorFor&lt;T&gt;(control, property, string.Empty);<br />}<br /><br />public static BaseValidator AddValidatorFor&lt;T&gt;(<br />    this Control control, Expression&lt;Func&lt;T, object&gt;&gt; property,<br />    string rulesetName)<br />{<br />    var validator = CreateValidatorFor(control, property,<br />        rulesetName);<br /><br />    AddValidatorToPageJustAfterControl(validator, control);<br /><br />    return validator;<br />}<br /><br />public static BaseValidator CreateValidatorFor&lt;T&gt;(<br />    this Control control, Expression&lt;Func&lt;T, object&gt;&gt; property)<br />{<br />    return CreateValidatorFor(control, property, string.Empty);<br />}<br /><br />public static BaseValidator CreateValidatorFor&lt;T&gt;(<br />    this Control control, Expression&lt;Func&lt;T, object&gt;&gt; property,<br />    string rulesetName)<br />{<br />    PropertyProxyValidator proxy = CreateNewProxyValidator();<br /><br />    proxy.ControlToValidate = control.ID;<br /><br />    BindProxyValidatorToDomainProperty(proxy, property,<br />        rulesetName);<br /><br />    return proxy;<br />}<br /><br />private static PropertyProxyValidator CreateNewProxyValidator()<br />{<br />    return new PropertyProxyValidator()<br />    {<br />        Display = ValidatorDisplay.Static,<br />    };<br />}<br /><br />private static void BindProxyValidatorToDomainProperty&lt;T&gt;(<br />    PropertyProxyValidator proxy,<br />    Expression&lt;Func&lt;T, object&gt;&gt; property, string rulesetName)<br />{<br />    proxy.PropertyName = GetPropertyName(property);<br />    proxy.SourceTypeName = typeof(T).AssemblyQualifiedName;<br />    proxy.RulesetName = rulesetName;<br />}<br /><br />private static string GetPropertyName(LambdaExpression property)<br />{<br />    var member = property.Body as MemberExpression;<br /><br />    if (member == null)<br />    {<br />        var unaryExpression = (UnaryExpression)property.Body;<br />        member = (MemberExpression)unaryExpression.Operand;<br />    }<br /><br />    return member.Member.Name;<br />}<br /><br />private static void AddValidatorToPageJustAfterControl(<br />    BaseValidator validator, Control control)<br />{<br />    int index = control.Parent.Controls.IndexOf(control);<br /><br />    try<br />    {<br />        control.Parent.Controls.AddAt(index + 1, validator);<br />    }<br />    catch (HttpException ex)<br />    {<br />        throw BuildMoreExpressiveException(control, ex);<br />    }<br />}<br /><br />private static Exception BuildMoreExpressiveException(<br />    Control control, HttpException exception)<br />{<br />    return new InvalidOperationException(string.Format(<br />        &quot;Sorry, you have encountered a rare .NET bug. &quot; +<br />        &quot;Control '{1}', which is the parent control of '{0}'&quot; + <br />        &quot;, contains '&lt;% %&gt;' tags. Because of the existance &quot; + <br />        &quot;of those tags, this parent control can not be &quot; + <br />        &quot;modified and it is impossible to dynamically add &quot; + <br />        &quot;validators to it. You can fix this by wrapping &quot; + <br />        &quot;'{0}' in another control. For instance: &quot; + <br />        &quot;&lt;asp:{2} runat='server' ID='{1}'&gt;&quot; +<br />            &quot;&lt;asp:PlaceHolder runat='server'&gt;&quot; + <br />                &quot;&lt;asp:{3} runat='server' id='{0}' /&gt;&quot; + <br />            &quot;&lt;/asp:PlaceHolder&gt;&quot; +<br />        &quot;&lt;/asp:{2}&gt;. {4}&quot;, control.ID, control.Parent.ID, <br />        control.Parent.GetType().Name, <br />        control.GetType().Name, exception.Message));<br />}<br /></pre><p>I think this code rather speaks for itself. When called, the method will create a new validator by binding to the control to validate and binding it to the property in the domain. After that it adds the validator to the page&rsquo;s control hierarchy.</p><p>This code has several other benefits. First of all, while working with a <span class="type">PropertyProxyValidator</span> internally, it returns the newly created instance by it&rsquo;s base type: <span class="type">BaseValidator</span>. This way we can prevent our presentation layer from having a direct dependency on the Validation Application Block, which is a good thing from an architectural perspective.</p><p>A second benefit is that we&rsquo;ve now centralized the creation of these validators and can customize the creation more easily. As you might know, the default behavior of the ASP.NET validators and therefore the <span class="type">PropertyProxyValidator</span> is to display the full error message inline. It would be more attractive when the validator would only show an image and allow the error message to be shown when the image is hovered with the mouse. With the current design we only have to change the <span class="code">CreateNewProxyValidator</span> method. Here is the improved implementation:</p><pre class="cs" language="csharp" customtypes="PropertyProxyValidator " customvaluetypes="ValidatorDisplay">private static PropertyProxyValidator CreateNewProxyValidator()<br />{<br />    var proxy = new PropertyProxyValidator()<br />    {<br />        Display = ValidatorDisplay.Static,<br />    };<br /><br />    // Let's make the proxy more fancy :-)<br />    proxy.Text = &quot;&lt;img src='http://www.cuttingedge.itstatus_failed_small.gif' /&gt;&quot;;<br /><br />    // Here is a little trick to set the title attribute<br />    // with the error message.<br />    proxy.PreRender += (sender, e) =&gt;<br />    {<br />        var title = proxy.ErrorMessage.Replace(&quot;&lt;br/&gt;&quot;, &quot;,&quot;);<br /><br />        if (title.Length &gt; 0 &amp;&amp; title[title.Length - 1] == ',')<br />        {<br />            title = title.Substring(0, title.Length - 1);<br />        }<br /><br />        proxy.Attributes[&quot;title&quot;] = title;<br />    };<br /><br />    return proxy;<br />}</pre><p>There is a bit dirty trickery going on in this method, because of how the <span class="type">PropertyProxyValidator</span> is implemented, but at least we&rsquo;re now able to change the look and feel of our application. You don&rsquo;t want to get this task assigned to you when all <span class="type">PropertyProxyValidator</span> were defined in markup.</p><p>Please note that the code presented in this post has one important drawback: it will fail miserably when we're trying to validate anything else than text, such as numbers, dates etc. Please read <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=79" title="Integrating Validation Application Block with ASP.NET part 2">part 2</a> for a solution to this problem.</p><p><font color="#ff0000"><font color="#000000">Please note that there is </font></font><font color="#ff0000"><font color="#000000"><a rel="external" href="http://www.west-wind.com/weblog/posts/5758.aspx" title="Rick Strahl's Web Log - The Controls collection cannot be modified because the control contains code blocks (i.e. &lt;% ... %&gt;). ">an important quirk</a> in</font></font><font color="#ff0000"><font color="#000000"> de design of ASP.NET that you might come across when implementing this solution. The exception message of the </font></font><span class="code">BuildMoreExpressiveException</span><font color="#ff0000"><font color="#000000"> method already gives it away. The solution proposed in this article works by injecting controls in to the page's control hierarchy. However, when an ASP.NET page contains &lt;% %&gt; code blocks, the collection of controls containing such a code block gets immutable and the line <span class="code">control.Parent.Controls.AddAt(index + 1, proxy);</span> will result in an <span class="type">HttpException</span>. You can work around this problem by wrapping the control that you want to validate with a server tag, such as an </font></font><span class="code">&lt;asp:PlaceHolder&gt;&lt;/asp:PlaceHolder</span><font color="#ff0000"><font color="#000000">&gt;. By throwing an exception with a very descriptive message, I'm hoping to save you and your fellow developers a lot of time, when you encounter this problem. </font></font></p><p>Happy validating!</p>
		]]></content>
		<author>
			<name>Steven</name>
		</author>
	</entry>
	
	
	
	<entry>
		<title>CuttingEdge.Conditions source used for MongoDB .NET Driver</title>
		<link rel="alternate" type="text/html" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=77" />
		<updated>2011-04-01T13:34:00+02:00</updated>
		<published>2010-06-28T17:40:00+02:00</published>
		<id>tag:pivotpowered,2012:NETJunkie.77</id>
		<link rel="related" type="text/html" href=""  />
		<summary type="text">Since I built CuttingEdge.Conditions, I had lots of positive reactions from developers who loved it. However, I've never saw the source code been reused in another library or framework; until now.</summary>
        <content type="html" xml:lang="en" xml:base="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=77"><![CDATA[
                Since I built <a rel="external" href="http://conditions.codeplex.com" title="CuttingEdge.Conditions">CuttingEdge.Conditions</a>, I had lots of positive reactions from developers who loved it. However, I've never saw the source code been reused in another library or framework; until now.<p><img src="http://www.cuttingedge.it/blogs/steven/images/conditions.jpg" style="float:right;margin-left:10px;margin-bottom:5px;border:1px solid" title="" alt="" class="pivot-image" />I just stumbled upon an exact copy of the CuttingEdge.Conditions <a rel="external" href="http://mongodb-net.googlecode.com/svn-history/r73/trunk/MongoDB.Driver/Platform/Conditions/" title="mongodb-net - Revision 73: /trunk/MongoDB.Driver/Platform/Conditions">source code</a> inside the <a rel="external" href="http://code.google.com/p/mongodb-net/" title="mongodb-net">MongoDB .NET Driver</a>. I am absolutely fine with this. I deliberately choose the MIT license which permits reuse of the code in any form. Reuse of my code is the biggest compliment a developer can give me, except of course compliments that involve money :-).</p>
		]]></content>
		<author>
			<name>Steven</name>
		</author>
	</entry>
	
	
	
	<entry>
		<title>Breaking changes in SmtpClient in .NET 4.0</title>
		<link rel="alternate" type="text/html" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=76" />
		<updated>2011-09-12T14:57:00+02:00</updated>
		<published>2010-05-06T15:41:00+02:00</published>
		<id>tag:pivotpowered,2012:NETJunkie.76</id>
		<link rel="related" type="text/html" href=""  />
		<summary type="text">In .NET 4.0 the SmtpClient class now implements IDisposable. This is a breaking change what you should watch out for.</summary>
        <content type="html" xml:lang="en" xml:base="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=76"><![CDATA[
                In .NET 4.0 the SmtpClient class now implements IDisposable. This is a breaking change what you should watch out for.<p><img src="http://www.cuttingedge.it/blogs/steven/images/breakingchains.jpg" style="float:right;margin-left:10px;margin-bottom:5px;border:1px solid" title="" alt="" class="pivot-image" />For .NET 4.0 the BCL team decided to pool SMTP connections, just as .NET already did with database connections. This of course means that the <a rel="external" href="http://msdn.microsoft.com/en-us/library/system.net.mail.smtpclient.aspx" title="MSDN System.Net.Mail.SmtpClient">SmtpClient</a> class should implement <span class="type">IDisposable</span>, just as the <span class="type">SqlConnection</span> does. When STMP connections are pooled, the overhead over establishing a new connection is lowered, which is a good thing. However, this is a breaking change. Migrating your code to .NET 4.0, without any changes, could lead to the same connection pool timeout exceptions as we're are used with database connections.</p><p>Perhaps there are more of these 'hidden jams' inside the new .NET 4.0 framework. So when migrating to .NET 4.0, it's wise to recompile your project and run FxCop over it. When your code isn't too complicated, FxCop will spot the places where you didn't dispose any disposable object. And you can already prepare your code like this:</p><pre class="cs" language="csharp" customtypes="SmtpClient" customvaluetypes="PutYourCustomValueTypesHere">var client = new SmtpClient();<br /><br />// Do not remove this using. In .NET 4.0<br />// SmtpClient implements IDisposable.<br />using (client as IDisposable)<br />{<br />    client.Send(message);<br />} <br /></pre><p>Good luck.</p>
		]]></content>
		<author>
			<name>Steven</name>
		</author>
	</entry>
	
	
	
	<entry>
		<title>Protecting against Regex DOS attacks</title>
		<link rel="alternate" type="text/html" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=75" />
		<updated>2010-05-05T12:14:00+02:00</updated>
		<published>2010-05-05T12:14:00+02:00</published>
		<id>tag:pivotpowered,2012:NETJunkie.75</id>
		<link rel="related" type="text/html" href=""  />
		<summary type="text">Bryan Sullivan describes in the May issue of his MSDN article a denial  of service attack that abuses regular expressions. As Bryan explains, a  poorly written regex can bring your server to its knees.</summary>
        <content type="html" xml:lang="en" xml:base="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=75"><![CDATA[
                Bryan Sullivan describes in the May issue of his MSDN article a denial  of service attack that abuses regular expressions. As Bryan explains, a  poorly written regex can bring your server to its knees.<p>Bryan demonstrates that even the simplest regular expressions can bring your server to its knees. Here are some examples of regular expressions that can easily cause this to happen:</p><pre class="cs">^(\d+)+$<br />^(\d+)*$<br />^(\d*)*$<br />^(\d+|\s+)*$<br />^(\d|\d\d)+$<br />^(\d|\d?)+$</pre><p>Read more about the causes and the cures <a rel="external" href="http://msdn.microsoft.com/nl-nl/magazine/ff646973%28en-us%29.aspx" title="MSDN - Regular Expression Denial of Service Attacks and Defenses">here</a>.</p>
		]]></content>
		<author>
			<name>Steven</name>
		</author>
	</entry>
	
	
	
	<entry>
		<title>Breaking changes in .NET 4.0</title>
		<link rel="alternate" type="text/html" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=74" />
		<updated>2010-04-13T08:28:00+02:00</updated>
		<published>2010-04-13T08:28:00+02:00</published>
		<id>tag:pivotpowered,2012:NETJunkie.74</id>
		<link rel="related" type="text/html" href=""  />
		<summary type="text">Microsoft published an interesting list of breaking changes in the just released .NET 4.0 framework.</summary>
        <content type="html" xml:lang="en" xml:base="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=74"><![CDATA[
                Microsoft published an interesting list of breaking changes in the just released .NET 4.0 framework.Read the <a rel="external" href="http://msdn.microsoft.com/en-us/library/ee941656%28VS.100%29.aspx" target="_blank" title=".NET Framework 4 Migration Issues">.NET Framework 4 Migration Issues</a> here.
		]]></content>
		<author>
			<name>Steven</name>
		</author>
	</entry>
	
	
	
	<entry>
		<title>Validator inheritance while using Validation Application Block configuration files</title>
		<link rel="alternate" type="text/html" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=73" />
		<updated>2011-06-22T21:11:00+02:00</updated>
		<published>2010-03-22T21:30:00+02:00</published>
		<id>tag:pivotpowered,2012:NETJunkie.73</id>
		<link rel="related" type="text/html" href=""  />
		<summary type="text">This article describes how to build an IConfigurationSource implementation that allows validators, defined in a base class or interface, to be inherited by subclasses and implementations.</summary>
        <content type="html" xml:lang="en" xml:base="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=73"><![CDATA[
                This article describes how to build an IConfigurationSource implementation that allows validators, defined in a base class or interface, to be inherited by subclasses and implementations.<p><a rel="external" href="http://msdn.microsoft.com/en-us/library/dd140088.aspx" title="Enterprise Library 4.1 - October 2008 The Validation Application Block">Enterprise Library Validation Application Block</a> (VAB) is a great framework. As I wrote before, it allows many complex scenario&rsquo;s. There&rsquo;s one shortcoming of VAB though, that I find particularly annoying. While it allows validation attributes to be inherited from base types to derived types, <a rel="external" href="http://entlib.codeplex.com/wikipage?title=Why%20do%20validators%20that%20are%20configured%20in%20the%20base%20class%20not%20work%20in%20its%20subclasses?&amp;referringTitle=EntLib%20FAQ" title="patterns &amp; practices &ndash; Enterprise Library FAQ - Why do validators that are configured in the base class not work in its subclasses?">inheritance is not supported for validations defined in configuration files</a>. This means that when validating a type, all validations defined through configuration on base classes of that type are ignored. Even the coming 5.0 release will lack this feature.</p><p>This behavior, or lack of functionally, is caused by the internal workings of VAB. While the internal <span class="type">MetadataValidatorBuilder</span> uses reflection on types to find the defined validators of a type, the internal <span class="type">ConfigurationValidatorBuilder</span> simply finds a type&rsquo;s validators by it&rsquo;s type name. From the perspective of the <span class="type">ConfigurationValidatorBuilder</span>, there are no types, just strings. For being able to find base types of a certain type, you need the .NET type system. In other words, the <span class="type">ConfigurationValidatorBuilder</span> would first need to create a <span class="type">Type</span> object from a string. And while the type name is mandatory in the VAB configuration system, the type&rsquo;s assembly name is optional. This makes creating an actual type rather time consuming, because all types in the current AppDomain need to be iterated and matched by there name.</p><p>According to the <a rel="external" href="http://entlib.codeplex.com/wikipage?title=Why%20do%20validators%20that%20are%20configured%20in%20the%20base%20class%20not%20work%20in%20its%20subclasses?&amp;referringTitle=EntLib%20FAQ" title="patterns &amp; practices &ndash; Enterprise Library FAQ - Why do validators that are configured in the base class not work in its subclasses?">Enterprise Library FAQ</a>, there actually is a simple solution to this problem:</p><blockquote>replicate the validation specification for the subclasses.</blockquote><p>This of course is a brittle and error prone solution. Every time you create a new derived type, you have to think about duplicating that logic. It&rsquo;s annoying and time consuming. There must be other possibilities.</p><p>In <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=65" title=".NET Junkie - Putting the Validation Application Block configuration in its own file">a previous article about VAB</a> I showed a way to validate a set of objects using VAB. The code looked like this:</p><pre class="cs" language="csharp" customtypes="ValidationResult Validator ValidationFactory" customvaluetypes="PutYourCustomValueTypesHere">public IEnumerable&lt;ValidationResult&gt; Validate(<br />    IEnumerable&lt;object&gt; entities)<br />{<br />    return<br />        from entity in entities<br />        let type = entity.GetType()<br />        let validator = CreateValidator(type)<br />        let results = validator.Validate(entity)<br />        where !results.IsValid<br />        from result in results<br />        select result;<br />}<br /><br />private static Validator CreateValidator(Type type)<br />{<br />    string ruleSet = string.Empty;<br /><br />    return ValidationFactory.CreateValidator(type, ruleSet,<br />        ConfigurationSource);<br />}</pre>  <p>The code iterates all given entities and validates each instance by retrieving the validator for the type of that instance. We can add quick and dirty inheritance support by also iterating the type hierarchy of each instance and validate that instance against the validator for that particular type:</p>   <pre class="cs" language="csharp" customtypes="ValidationResult Validator ValidationFactory" customvaluetypes="PutYourCustomValueTypesHere">public IEnumerable&lt;ValidationResult&gt; Validate(<br />    IEnumerable&lt;object&gt; entities)<br />{<br />    return<br />        from entity in entities<br />        from type in GetTypeHierarchyOf(entity.GetType())<br />        let validator = CreateValidator(type)<br />        let results = validator.Validate(entity)<br />        where !results.IsValid<br />        from result in results<br />        select result;<br />}<br />    <br />// Return the type and all its base types<br />private static IEnumerable&lt;Type&gt; GetTypeHierarchyOf(Type type)<br />{<br />    while (type != null)<br />    {<br />        yield return type;<br />        type = type.BaseType;<br />    }<br />}</pre><p>While this seems easy and great, there are a couple of problems with this code. First of all this code generates duplicate error messages with attribute based validation. Reason for this is that inheritance is already supported by VAB for attribute based validation. Second, when validating graphs of objects using the <span class="code">[</span><span class="type">ObjectValidator</span><span class="code">]</span> and <span class="code">[</span><span class="type">ObjectCollectionValidator</span><span class="code">]</span>, validations of base types will not be checked. Reason for this is that the <span class="type">ObjectValidator</span> and <span class="type">ObjectCollectionValidator</span> simply request a validator for the current type, and not for the type and al its base types.</p><p>Although the given code might work in certain scenario&rsquo;s, the lack of object graph validation is a pretty big drawback. Let&rsquo;s take a totally different approach here.</p><p>When you read my previous article about <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=72" title=".NET Junkie - Splitting up Validation Application Block configuration into multiple files">merging multiple configuration files into a single VAB configuration</a>, you know a lot can be done by rebuilding <span class="type">ValidationSettings</span> objects. Using this exact approach we can create a solution to this inheritance problem. Note however, that this takes an awful lot more code than what was needed with the previous code snippet. Nice thing though is that I can reuse a lot of my code from my previous article.</p><p><em><strong>Please note that when you want to use the code in this article, you will also need the code of <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=72" title=".NET Junkie - Splitting up Validation Application Block  configuration into multiple files">my previous article</a>, because I won&rsquo;t repeat it here.</strong></em><br /><br />Please also note that while the solution below works pretty well, the solution itself has some shortcomings. Please note the following:</p><ul><li>While the solution even allows validations defined on interfaces to work on implementations of that interface, validation might fail when members are implemented explicitly.</li><li>The solution iterates all types in all referenced assemblies of the current AppDomain, to find out whether a type derives from a certain base type. This means that the solution will not work for types that are generated during runtime and types in assemblies that are loaded dynamically.</li><li>The solution creates a new <span class="type">ValidationSettings</span> configuration where it adds all derived types of a base type in the configuration. When many such types exist, the generation process could become time consuming and could take a lot of memory. For instance, don&rsquo;t add the .NET interfaces <span class="type">IComparable</span>, <span class="type">IConvertible</span>, <span class="type">IFormattable</span>, <span class="type">ISerializable</span>, and <span class="type">IDisposable</span> to the configuration :-)</li></ul>These short comes can probably only be solved when the Enterprise Library get native support for configuration inheritance. So until that moment has come, the code below can save your day.<br /><p>Below is the implementation of the <span class="type">InheritanceValidationConfigurationSource</span>. It is in fact a decorator that wraps a supplied <span class="type">IConfigurationSource</span>. Within the constructor the construction of the new &lsquo;flattened&rsquo; configuration is delegated to the <span class="type">ValidationSettingsTypeHierarchyFlattener</span> class. The returned <span class="type">ValidationSettings</span> object is cached and returned on each call to <span class="code">GetSection</span>.</p><pre class="cs" language="csharp" customtypes="InheritanceValidationConfigurationSource IConfigurationSource ValidationSettings ValidationSettingsTypeHierarchyFlattener " customvaluetypes="PutYourCustomValueTypesHere">public class InheritanceValidationConfigurationSource<br />    : IConfigurationSource<br />{<br />    private readonly ValidationSettings flattenedValidationSettings;<br /><br />    public InheritanceValidationConfigurationSource(<br />        IConfigurationSource source)<br />    {<br />        var settings = source.GetSection(ValidationSettings.SectionName)<br />            as ValidationSettings;<br /><br />        this.flattenedValidationSettings =<br />            ValidationSettingsTypeHierarchyFlattener.Flatten(settings);<br />    }<br /><br />    public ConfigurationSection GetSection(string sectionName)<br />    {<br />        if (sectionName == ValidationSettings.SectionName)<br />        {<br />            return this.flattenedValidationSettings;<br />        }<br /><br />        return null;<br />    }<br /><br />    #region IConfigurationSource Members<br /><br />    // Rest of the IConfigurationSource members left out.<br />    // Just implement them by throwing an exception from<br />    // their bodies; they are not used.<br /><br />    #endregion<br />}</pre><p>Below is the code of the <span class="type">ValidationSettingsTypeHierarchyFlattener</span> class. Its logic is rather straightforward. It starts by making a copy of the supplied <span class="type">ValidationSettings</span>. By making a copy, the original settings stay unmodified. Next, it finds all (non-interface) types in the configuration that have no base types in the configuration: the root types. For each root type the inheritance tree is walked (breadth-first) and for each type in that tree the configuration of its base type is copied to / merged with that type. The type is added to the configuration when it doesn&rsquo;t exist. The last step in the flattener&rsquo;s logic is finding all interface types in the configuration. For each interface type, all implementations (in the current AppDomain) are iterated and the configuration of that interface is copied to / merged with that type. Here is the code:</p><pre class="cs" language="csharp" customtypes="ValidationSettingsTypeHierarchyFlattener ValidationSettings Copier TypeFinder DistanceToBaseTypeComparer ValidatedTypeReference TypeMerger ConfigurationErrorsException CultureInfo" customvaluetypes="PutYourCustomValueTypesHere">internal class ValidationSettingsTypeHierarchyFlattener<br />{<br />    private readonly ValidationSettings settings;<br /><br />    private ValidationSettingsTypeHierarchyFlattener(<br />        ValidationSettings settings)<br />    {<br />        this.settings = Copier.MakeCopy(settings);<br />    }<br /><br />    public static ValidationSettings Flatten(ValidationSettings settings)<br />    {<br />        var flattener =<br />            new ValidationSettingsTypeHierarchyFlattener(settings);<br /><br />        flattener.DuplicateConfigurationForDerivedTypes();<br /><br />        flattener.DuplicateInterfaceConfigurationToImplementations();<br /><br />        return flattener.settings;<br />    }<br /><br />    private void DuplicateConfigurationForDerivedTypes()<br />    {<br />        var rootClasses = this.FindRootClassesInConfiguration();<br /><br />        foreach (Type rootClass in rootClasses)<br />        {<br />            this.DuplicateConfigurationToDerivedTypesOf(rootClass);<br />        }<br />    }<br /><br />    private void DuplicateConfigurationToDerivedTypesOf(Type root)<br />    {<br />        var unorderedDescendants =<br />            TypeFinder.GetDerivedClassesFor(root);<br /><br />        var sorter = new DistanceToBaseTypeComparer(root);<br /><br />        var descendants = unorderedDescendants.OrderBy(t =&gt; t, sorter);<br /><br />        foreach (Type descendant in descendants)<br />        {<br />            this.DuplicateConfigurationTo(descendant);<br />        }<br />    }<br /><br />    private void DuplicateConfigurationTo(Type descendant)<br />    {<br />        ValidatedTypeReference baseReference =<br />            this.settings.Types.Get(descendant.BaseType.FullName);<br /><br />        ValidatedTypeReference descendantReference =<br />            this.settings.Types.Get(descendant.FullName);<br /><br />        bool descendantAlreadyExistsInConfiguration =<br />            descendantReference != null;<br /><br />        if (descendantAlreadyExistsInConfiguration)<br />        {<br />            new TypeMerger(this.settings, baseReference)<br />                .MergeInto(descendantReference);<br />        }<br />        else<br />        {<br />            var copy =<br />                MakeCopyOfReferenceForType(baseReference, descendant);<br /><br />            this.settings.Types.Add(copy);<br />        }<br />    }<br /><br />    private void DuplicateInterfaceConfigurationToImplementations()<br />    {<br />        var interfaces = this.FindInterfacesInConfiguration();<br /><br />        foreach (Type intrface in interfaces)<br />        {<br />            this.DuplicateConfigurationForImplementationsOf(intrface);<br />        }<br />    }<br /><br />    private void DuplicateConfigurationForImplementationsOf(Type intrface)<br />    {<br />        var implementations =<br />            TypeFinder.GetImplementationsOfInterface(intrface);<br /><br />        foreach (Type implementation in implementations)<br />        {<br />            this.DuplicateConfigurationForImplementation(intrface,<br />                implementation);<br />        }<br />    }<br /><br />    private void DuplicateConfigurationForImplementation(Type intrface,<br />        Type implementation)<br />    {<br />        ValidatedTypeReference interfaceReference =<br />            this.settings.Types.Get(intrface.FullName);<br /><br />        ValidatedTypeReference implementationReference =<br />            this.settings.Types.Get(implementation.FullName);<br /><br />        bool implementationAlreadyExistsInConfiguration =<br />            implementationReference != null;<br /><br />        if (implementationAlreadyExistsInConfiguration)<br />        {<br />            new TypeMerger(this.settings, interfaceReference)<br />                .MergeInto(implementationReference);<br />        }<br />        else<br />        {<br />            var copy = MakeCopyOfReferenceForType(interfaceReference,<br />                implementation);<br /><br />            this.settings.Types.Add(copy);<br />        }<br />    }<br /><br />    private Type[] FindRootClassesInConfiguration()<br />    {<br />        var configuredTypes = new HashSet&lt;Type&gt;(this.GetConfiguredTypes());<br /><br />        return<br />            (from configuredType in configuredTypes<br />             where !configuredType.IsInterface<br />             where IsRootType(configuredType, configuredTypes)<br />             select configuredType).ToArray();<br />    }<br /><br />    private Type[] FindInterfacesInConfiguration()<br />    {<br />        var configuredTypes = new HashSet&lt;Type&gt;(this.GetConfiguredTypes());<br /><br />        return<br />            (from configuredType in configuredTypes<br />             where configuredType.IsInterface<br />             select configuredType).ToArray();<br />    }<br /><br />    private static bool IsRootType(Type type, HashSet&lt;Type&gt; configuredTypes)<br />    {<br />        var baseTypesForTypeInConfiguration =<br />            from baseType in GetBaseTypesFor(type)<br />            where configuredTypes.Contains(baseType)<br />            select baseType;<br /><br />        return !baseTypesForTypeInConfiguration.Any();<br />    }<br /><br />    private static IEnumerable&lt;Type&gt; GetBaseTypesFor(Type type)<br />    {<br />        Type baseType = type.BaseType;<br /><br />        while (baseType != null)<br />        {<br />            yield return baseType;<br />            baseType = baseType.BaseType;<br />        }<br />    }<br /><br />    private IEnumerable&lt;Type&gt; GetConfiguredTypes()<br />    {<br />        return<br />            from reference in this.settings.Types<br />            select GetTypeFromReference(reference);<br />    }<br /><br />    private static ValidatedTypeReference MakeCopyOfReferenceForType(<br />        ValidatedTypeReference reference, Type targetType)<br />    {<br />        var copy = Copier.MakeCopy(reference);<br /><br />        copy.Name = targetType.FullName;<br />        copy.AssemblyName = targetType.Assembly.FullName;<br /><br />        return copy;<br />    }<br /><br />    private static Type GetTypeFromReference(<br />        ValidatedTypeReference reference)<br />    {<br />        // VAB doesn't need AssemblyName in order to validate a type.<br />        if (!String.IsNullOrEmpty(reference.AssemblyName))<br />        {<br />            // Fast O(1) lookup with assembly name.<br />            return GetTypeFromReferenceByFullyQualifiedName(reference);<br />        }<br />        else<br />        {<br />            // Slow lookup, but needed when AssemblyName is missing.<br />            return GetTypeFromReferenceByName(reference);<br />        }<br />    }<br /><br />    private static Type GetTypeFromReferenceByFullyQualifiedName(<br />        ValidatedTypeReference reference)<br />    {<br />        var fqn = reference.Name + &quot;, &quot; + reference.AssemblyName;<br /><br />        try<br />        {<br />            const bool ThrowOnError = true;<br />            return Type.GetType(fqn, ThrowOnError);<br />        }<br />        catch (Exception ex)<br />        {<br />            throw new ConfigurationErrorsException(<br />                string.Format(CultureInfo.InvariantCulture,<br />                &quot;The configuration file references a type '{0}' &quot; +<br />                &quot;that could not be found in the AppDomain. {1}&quot;,<br />                fqn, ex.Message), ex);<br />        }<br />    }<br /><br />    private static Type GetTypeFromReferenceByName(<br />        ValidatedTypeReference reference)<br />    {<br />        var typesWithName =<br />            TypeFinder.GetAllTypesInCurrentAppDomain()<br />                .Where(t =&gt; t.FullName == reference.Name)<br />                .ToArray();<br /><br />        if (typesWithName.Length == 1)<br />        {<br />            return typesWithName[0];<br />        }<br /><br />        if (typesWithName.Length &gt; 1)<br />        {<br />            throw new ConfigurationErrorsException(<br />                string.Format(CultureInfo.InvariantCulture,<br />                &quot;The configuration file references a type '{0}' &quot; +<br />                &quot;that is found multiple times in the current App&quot; +<br />                &quot;Domain. Try specifying the AssemblyName as well.&quot;,<br />                reference.Name));<br />        }<br />        else<br />        {<br />            throw new ConfigurationErrorsException(<br />                string.Format(CultureInfo.InvariantCulture,<br />                &quot;The configuration file references a type '{0}' &quot; +<br />                &quot;that could not be found in the AppDomain.&quot;,<br />                reference.Name));<br />        }<br />    }<br />}</pre><p>The flattener class references the small <span class="type">TypeFinder</span> helper class. This class contains a few utility methods that search for types. For instance it enables loading all derived types of a particular type or finding all implementations of a particular interface. Below is the code for the <span class="type">TypeFinder</span> class:</p><pre class="cs" language="csharp" customtypes="TypeFinder ReflectionTypeLoadException DebuggerStepThrough" customvaluetypes="PutYourCustomValueTypesHere">internal static class TypeFinder<br />{<br />    public static IEnumerable&lt;Type&gt; GetAllTypesInCurrentAppDomain()<br />    {<br />        return<br />            from assembly in AppDomain.CurrentDomain.GetAssemblies()<br />            from type in GetAllTypesFor(assembly)<br />            select type;<br />    }<br /><br />    public static IEnumerable&lt;Type&gt; GetDerivedClassesFor(Type baseType)<br />    {<br />        return<br />            from type in GetAllTypesInCurrentAppDomain()<br />            where type.IsClass<br />            where type.IsSubclassOf(baseType)<br />            select type;<br />    }<br /><br />    public static IEnumerable&lt;Type&gt; GetImplementationsOfInterface(<br />        Type interfaceType)<br />    {<br />        return<br />            from type in GetAllTypesInCurrentAppDomain()<br />            where !type.IsInterface<br />            where interfaceType.IsAssignableFrom(type)<br />            select type;<br />    }<br /><br />    [DebuggerStepThrough]<br />    public static Type[] GetAllTypesFor(Assembly assembly)<br />    {<br />        try<br />        {<br />            return assembly.GetTypes();<br />        }<br />        catch (ReflectionTypeLoadException)<br />        {<br />            // GetTypes could throw an ReflectionTypeLoadException.<br />            // In that case we just skip the assembly.<br />            return Type.EmptyTypes;<br />        }<br />    }<br />}</pre><p>As I described earlier, the <span class="type">ValidationSettingsTypeHierarchyFlattener</span> walks the inheritance tree of a particular type in breadth-first order. While depth-first would also work, processing the collection of types in the hierarchy must have a certain order. By making sure a certain type is always processed after its base type, it allows us to copy the complete configuration from the type&rsquo;s base type. Copying configuration becomes a waterfall where all configuration flows down the hierarchy. Not doing it this way, would make it very hard to yield correct results.</p><p>Because the <span class="type">TypeFinder</span> class does not return the list of base types in a guaranteed order, the flattener class orders the list. It uses the <span class="type">DistanceToBaseTypeComparer</span> class for this. This comparer compares two types based on their distance to the supplied base type. Here is the implementation:</p><pre class="cs" language="csharp" customtypes="DistanceToBaseTypeComparer InvalidProgramException CultureInfo" customvaluetypes="PutYourCustomValueTypesHere">internal sealed class DistanceToBaseTypeComparer : IComparer&lt;Type&gt;<br />{<br />    private readonly Type root;<br /><br />    public DistanceToBaseTypeComparer(Type root)<br />    {<br />        this.root = root;<br />    }<br /><br />    public int Compare(Type x, Type y)<br />    {<br />        int distanceOfX = this.CalculateDistanceToRoot(x);<br />        int distanceOfY = this.CalculateDistanceToRoot(y);<br /><br />        return distanceOfX.CompareTo(distanceOfY);<br />    }<br /><br />    private int CalculateDistanceToRoot(Type derivedType)<br />    {<br />        if (this.root.IsInterface)<br />        {<br />            return this.CalculateDistanceToInterface(derivedType);<br />        }<br />        else<br />        {<br />            return this.CalculateDistanceToBaseType(derivedType);<br />        }<br />    }<br /><br />    private int CalculateDistanceToInterface(Type derivedType)<br />    {<br />        int distance = 1;<br /><br />        this.CheckIfTypeIsImplementationOfRoot(derivedType);<br /><br />        var baseType = derivedType.BaseType;<br /><br />        while (baseType != null &amp;&amp; this.root.IsAssignableFrom(baseType))<br />        {<br />            distance++;<br /><br />            baseType = baseType.BaseType;<br />        }<br /><br />        return distance;<br />    }<br /><br />    private int CalculateDistanceToBaseType(Type derivedType)<br />    {<br />        int distance = 0;<br /><br />        while (derivedType != this.root)<br />        {<br />            derivedType = derivedType.BaseType;<br />            distance++;<br />        }<br /><br />        return distance;<br />    }<br /><br />    private void CheckIfTypeIsImplementationOfRoot(Type derivedType)<br />    {<br />        if (!this.root.IsAssignableFrom(derivedType))<br />        {<br />            throw new InvalidProgramException(<br />                string.Format(CultureInfo.InvariantCulture,<br />                &quot;An internal error occurred. Type {0} is not an &quot; +<br />                &quot;implementation of interface {1}.&quot;,<br />                derivedType, this.root));<br />        }<br />    }<br />}</pre><p>The last two classes missing from the equation are the <span class="type">Copier</span> and <span class="type">TypeMerger</span> classes. You can find them in <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=72" title=".NET Junkie - Splitting up Validation Application Block configuration into multiple files">my previous article</a>.</p><p>Happy validating!</p>
		]]></content>
		<author>
			<name>Steven</name>
		</author>
	</entry>
	
	
	
	<entry>
		<title>Splitting up Validation Application Block configuration into multiple files</title>
		<link rel="alternate" type="text/html" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=72" />
		<updated>2011-03-31T00:20:00+02:00</updated>
		<published>2010-03-05T12:05:00+02:00</published>
		<id>tag:pivotpowered,2012:NETJunkie.72</id>
		<link rel="related" type="text/html" href=""  />
		<summary type="text">This article describes how to build an IConfigurationSource implementation that allows reading multiple configuration files that each contain part of the total Enterprise Library Validation Application Block configuration.</summary>
        <content type="html" xml:lang="en" xml:base="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=72"><![CDATA[
                This article describes how to build an IConfigurationSource implementation that allows reading multiple configuration files that each contain part of the total Enterprise Library Validation Application Block configuration.<p>Five months ago I <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=65" title=".NET Junkie - Putting the Validation Application Block configuration in its own file">wrote</a> about extracting the <a rel="external" href="http://msdn.microsoft.com/en-us/library/dd140088.aspx" title="Enterprise Library 4.1 - October 2008 The Validation Application Block">Enterprise Library Validation Application Block</a> (VAB for short) configuration to its own file. This is useful in situations where the configuration file gets big or, as I explained in the article, when you want to have unit tests supporting those validations. While you can use the same technique to put the different Enterprise Library blocks in their own configuration file, I want to take this one step further and allow the single VAB configuration to be split up into multiple configuration files. While I haven't tested this, I expect this technique to also work with the other application blocks.</p><p>Separating your VAB configuration into multiple files is useful in scenario&rsquo;s where the configuration gets very big or when dealing with <a rel="external" href="http://en.wikipedia.org/wiki/Software_as_a_service" title="Wikipedia - Software as a Service">Software as a Service</a> applications. With SaaS you&rsquo;d usually have multiple customers using the same web service or web application or perhaps even have multiple physical deployments (one per customer) for the same application / code base. Splitting up the configuration is useful when you have different validation requirements among your customers. The idea is to have one base configuration that contains the validations that hold for all customers and multiple specific configurations; one per customer.</p><p>It shouldn&rsquo;t come as an surprise that this scenario isn&rsquo;t supported out of the box. Despite the fact that the solution will not be a one-liner, it&rsquo;s great that the extensibility of VAB allows us to actually do this. The trick is to create an implementation of the <a rel="external" href="http://msdn.microsoft.com/en-us/library/microsoft.practices.enterpriselibrary.common.configuration.iconfigurationsource%28BTS.10%29.aspx" title="MSDN - IConfigurationSource interface">IConfigurationSource</a> interface that allows loading multiple configuration files and can merge them to one <span class="type">ValidationSettings</span> element which the VAB infrastructure is able to process.</p><p>In the code snippet below you can see the usage of the class I called <span class="type">ValidationConfigurationSourceCombiner</span>. It implements <span class="type">IConfigurationSource</span> and therefore allows it to be supplied as input to the validation process. It allows multiple <span class="type">IConfigurationSource</span> instances to be supplied through its constructor. During its creation it will combine the supplied configurations together to one big configuration, by iterating and comparing all elements and sub elements of these configurations.</p><pre class="cs" language="csharp" customtypes="IConfigurationSource ValidationConfigurationSourceCombiner FileConfigurationSource" customvaluetypes="PutYourCustomValueTypesHere">IConfigurationSource configurationSource =<br />    new ValidationConfigurationSourceCombiner(<br />        new FileConfigurationSource(&quot;validation_base.config&quot;),<br />        new FileConfigurationSource(&quot;validation_cust_13.config&quot;),<br />        new FileConfigurationSource(&quot;validation_cust_56.config&quot;)<br />    );</pre><p>Although the example uses a static list of configuration files, you can also load them dynamically for instance by searching the filesystem for all <em>validation_*.config</em> files, as shown here:</p><pre class="cs" language="csharp" customtypes="AppDomain IConfigurationSource ValidationConfigurationSourceCombiner FileConfigurationSource Directory" customvaluetypes="PutYourCustomValueTypesHere">var appDir = AppDomain.CurrentDomain.BaseDirectory;<br />var pattern = &quot;validation_*.config&quot;;<br /><br />IConfigurationSource configurationSource =<br />    new ValidationConfigurationSourceCombiner(<br />        from fileName in Directory.GetFiles(appDir, pattern)<br />        select new FileConfigurationSource(fileName) <br />            as IConfigurationSource<br />    ); <br /></pre><p>When you create a single combiner that holds all validations for all customers, you will have to differentiate by using customer specific rulesets and inform the validator that only the <em>default</em> and <em>cusomerX</em> rulesets have to be validated. Specifying customer specific rulesets however, can be error prone. Your other option would be to create a combiner per customer. You can store them in a dictionary with the customer id as key and supply the customer&rsquo;s specific combiner to the VAB validator.</p><p>Because the class takes <span class="type">IConfigurationSource</span> instances and implements <span class="type">IConfigurationSource</span> itself, it can by itself be used again as input to yet another combiner. This allows you to do infinitely stacking of instances :-).</p><p>Below the code for the <span class="type">ValidationConfigurationSourceCombiner</span>.</p><pre class="cs" language="csharp" customtypes="ValidationConfigurationSourceCombiner IConfigurationSource ValidationSettings ConfigurationSection TypeMerger Copier ValidationSettingsMerger" customvaluetypes="PutYourCustomValueTypesHere">public class ValidationConfigurationSourceCombiner<br />    : IConfigurationSource<br />{<br />    private readonly ValidationSettings combinedSettings;<br /><br />    public ValidationConfigurationSourceCombiner(<br />        params IConfigurationSource[] sources)<br />        : this((IEnumerable&lt;IConfigurationSource&gt;)sources)<br />    {<br />    }<br /><br />    public ValidationConfigurationSourceCombiner(<br />        IEnumerable&lt;IConfigurationSource&gt; sources)<br />    {<br />        string sectionName = ValidationSettings.SectionName;<br /><br />        var settings =<br />            from source in sources<br />            select source.GetSection(sectionName)<br />                as ValidationSettings;<br /><br />        this.combinedSettings =<br />            settings.Aggregate(CombineSettings);<br />    }<br /><br />    public ConfigurationSection GetSection(string sectionName)<br />    {<br />        if (sectionName == ValidationSettings.SectionName)<br />        {<br />            return this.combinedSettings;<br />        }<br /><br />        return null;<br />    }<br /><br />    #region IConfigurationSource Members<br /><br />    // Rest of the IConfigurationSource members left out.<br />    // Just implement them by throwing an exception from<br />    // their bodies; they are not used.<br /><br />    #endregion<br /><br />    private static ValidationSettings CombineSettings(<br />        ValidationSettings left, ValidationSettings right)<br />    {<br />        var valCopy = Copier.MakeCopy(left);<br /><br />        new ValidationSettingsMerger(right).MergeInto(valCopy);<br /><br />        return valCopy;<br />    }<br />}<br /></pre><p>As you can see this class doesn&rsquo;t really do much. The constructor processes the supplied <span class="type">IConfigurationSource</span> instances, by aggregating them down to a single <span class="type">ValidationSettings</span> object and the <span class="code">GetSection</span> method returns that instance. The <span class="type">Enumerable</span><span class="code">.Aggregate</span> method uses the <span class="code">CombineSettings</span> method, which takes two <span class="type">ValidationSettings</span> instances and produces a new <span class="type">ValidationSettings</span> that contains settings from both the instances. This is done by making a (deep) copy of the left and adding all settings from the right to that copy.</p><p>This adding (or merging as I call it in the code) is done by the <span class="type">ValidationSettingsMerger</span> class, which simply iterates over all the items in the settings object. For each item it checks if the target object already contains the item. If the target item is missing, a deep copy of the source item is made and that copy is added to the target&rsquo;s item collection. When the item already exists, the source item is merged with the target item. This merging is done by executing the operation described in this paragraphs for the item&rsquo;s sub items.</p><p>To complete this story, here is the rest of the implementation.</p><p>As always: happy validating!</p><pre class="cs" language="csharp" customtypes="IMerger ValidationMerger NamedConfigurationElement ValidationSettings ValidatedTypeReference Copier ConfigurationErrorsException RulesetMerger ValidationRulesetData NamedElementCollection ValidatedMemberReference ValidatorDataCollection ValidatorMerger ValidatorData ValidatorDataCollection MemberMerger CultureInfo ValidationSettingsMerger SuppressMessage TypeMerger" customvaluetypes="PutYourCustomValueTypesHere">internal interface IMerger<br />{<br />    string TypeName { get; }<br /><br />    string Name { get; }<br />    <br />    IMerger Parent { get; }<br />}<br /><br />internal class ValidationSettingsMerger<br />{<br />    private readonly ValidationSettings source;<br /><br />    public ValidationSettingsMerger(ValidationSettings source)<br />    {<br />        this.source = source;<br />    }<br /><br />    public void MergeInto(ValidationSettings target)<br />    {<br />        foreach (var sourceType in this.source.Types)<br />        {<br />            var targetType = target.Types.Get(sourceType.Name);<br /><br />            bool typeAlreadyInTarget = targetType != null;<br /><br />            if (typeAlreadyInTarget)<br />            {<br />                var merger = new TypeMerger(this.source, sourceType);<br />                merger.MergeInto(targetType);<br />            }<br />            else<br />            {<br />                target.Types.Add(Copier.MakeCopy(sourceType));<br />            }<br />        }<br />    }<br />}<br /><br />internal abstract class ValidationMerger&lt;T&gt; : IMerger<br />    where T : NamedConfigurationElement<br />{<br />    protected ValidationMerger(ValidationSettings settings,<br />        T sourceElement, IMerger parent)<br />    {<br />        this.SourceSettings = settings;<br />        this.Source = sourceElement;<br />        this.Parent = parent;<br />    }<br /><br />    public abstract string TypeName { get; }<br /><br />    public IMerger Parent { get; private set; }<br /><br />    public string Name { get { return this.Source.Name; } }<br /><br />    protected T Source { get; private set; }<br /><br />    protected ValidationSettings SourceSettings<br />    {<br />        get;<br />        private set;<br />    }<br />}<br /><br />internal class TypeMerger<br />    : ValidationMerger&lt;ValidatedTypeReference&gt;<br />{<br />    public TypeMerger(ValidationSettings sourceSettings,<br />        ValidatedTypeReference sourceType)<br />        : base(sourceSettings, sourceType, null)<br />    {<br />    }<br /><br />    public override string TypeName { get { return &quot;type&quot;; } }<br /><br />    public void MergeInto(ValidatedTypeReference target)<br />    {<br />        this.SetDefaultRuleset(target);<br /><br />        foreach (var sourceRules in this.Source.Rulesets)<br />        {<br />            var targetRules =<br />                target.Rulesets.Get(sourceRules.Name);<br /><br />            if (targetRules != null)<br />            {<br />                this.CreateRulesetMerger(sourceRules)<br />                    .MergeInto(targetRules);<br />            }<br />            else<br />            {<br />                targetRules = Copier.MakeCopy(sourceRules);<br />                target.Rulesets.Add(targetRules);<br />            }<br />        }<br />    }<br /><br />    private void SetDefaultRuleset(ValidatedTypeReference target)<br />    {<br />        var sourceRuleset = this.Source.DefaultRuleset;<br />        var targetRuleset = target.DefaultRuleset;<br /><br />        if (String.IsNullOrEmpty(targetRuleset))<br />        {<br />            target.DefaultRuleset = sourceRuleset;<br />        }<br />        else if (String.IsNullOrEmpty(sourceRuleset))<br />        {<br />            // Don't override the target ruleset.<br />        }<br />        else if (sourceRuleset != targetRuleset)<br />        {<br />            this.ThrowDefaultRulesetsDifferException(target);<br />        }<br />    }<br /><br />    private void ThrowDefaultRulesetsDifferException(<br />        ValidatedTypeReference target)<br />    {<br />        // Note: because the merging we loose the Element-<br />        // Information of the target, so we can not use it<br />        // the exception message.<br />        throw new ConfigurationErrorsException(<br />            string.Format(CultureInfo.InvariantCulture,<br />            &quot;The configuration file {0} contains a type &quot; +<br />            &quot;'{1}' that has a DefaultRuleset that differs &quot; +<br />            &quot;from the DefaultRuleset in the type of the &quot; +<br />            &quot;other configuration files. DefaultRuleset &quot; +<br />            &quot;'{2}' was expected but '{3}' was found.&quot;,<br />            this.Source.ElementInformation.Source,<br />            target.Name, this.Source.DefaultRuleset, <br />            target.DefaultRuleset));<br />    }<br /><br />    private RulesetMerger CreateRulesetMerger(<br />        ValidationRulesetData sourceRuleset)<br />    {<br />        return new RulesetMerger(this.SourceSettings,<br />            sourceRuleset, this);<br />    }<br />}<br /><br />internal class RulesetMerger<br />    : ValidationMerger&lt;ValidationRulesetData&gt;<br />{<br />    public RulesetMerger(ValidationSettings settings,<br />        ValidationRulesetData sourceRuleset, IMerger parent)<br />        : base(settings, sourceRuleset, parent)<br />    {<br />    }<br /><br />    public override string TypeName { get { return &quot;ruleset&quot;; } }<br /><br />    public void MergeInto(ValidationRulesetData target)<br />    {<br />        var source = this.Source;<br /><br />        this.MergeCollection(source.Fields, target.Fields);<br />        this.MergeCollection(source.Methods, target.Methods);<br />        this.MergeCollection(source.Properties, target.Properties);<br />        this.MergeValidators(source.Validators, target.Validators);<br />    }<br /><br />    private void MergeCollection&lt;TMember&gt;(<br />        NamedElementCollection&lt;TMember&gt; sourceCollection,<br />       NamedElementCollection&lt;TMember&gt; targetCollection)<br />        where TMember : ValidatedMemberReference, new()<br />    {<br />        foreach (var sourceMember in sourceCollection)<br />        {<br />            var targetMember =<br />                targetCollection.Get(sourceMember.Name);<br /><br />            if (targetMember != null)<br />            {<br />                this.CreateMemberMerger(sourceMember)<br />                    .MergeInto(targetMember);<br />            }<br />            else<br />            {<br />                targetMember = Copier.MakeCopy(sourceMember);<br />                targetCollection.Add(targetMember);<br />            }<br />        }<br />    }<br /><br />    private void MergeValidators(<br />        ValidatorDataCollection sourceValidators,<br />        ValidatorDataCollection targetValidators)<br />    {<br />        var merger = this.CreateValidatorMerger();<br />        merger.MergeValidatorsInto(<br />            sourceValidators, targetValidators);<br />    }<br /><br />    private MemberMerger&lt;TMemberReference&gt;<br />        CreateMemberMerger&lt;TMemberReference&gt;(<br />        TMemberReference sourceElement)<br />        where TMemberReference : ValidatedMemberReference, new()<br />    {<br />        return new MemberMerger&lt;TMemberReference&gt;(<br />            this.SourceSettings, sourceElement, this);<br />    }<br /><br />    private ValidatorMerger CreateValidatorMerger()<br />    {<br />        return new ValidatorMerger(this.SourceSettings, this);<br />    }<br />}<br /><br />internal class MemberMerger&lt;TMember&gt;<br />    : ValidationMerger&lt;ValidatedMemberReference&gt;<br />    where TMember : ValidatedMemberReference, new()<br />{<br />    public MemberMerger(ValidationSettings sourceSettings,<br />        TMember sourceMember, IMerger parent)<br />        : base(sourceSettings, sourceMember, parent)<br />    {<br />    }<br /><br />    [SuppressMessage(&quot;Microsoft.Globalization&quot;, <br />        &quot;CA1308:NormalizeStringsToUppercase&quot;)]<br />    public override string TypeName<br />    {<br />        get<br />        {<br />            // Allow returning the actual type without<br />            // subclassing the MemberMerger&lt;TMember&gt;.<br />            return typeof(TMember).Name<br />                .Replace(&quot;Validated&quot;, string.Empty)<br />                .Replace(&quot;Reference&quot;, string.Empty)<br />                .ToLowerInvariant();<br />        }<br />    }<br /><br />    public void MergeInto(TMember target)<br />    {<br />        var merger = this.CreateValidatorMerger();<br /><br />        merger.MergeValidatorsInto(this.Source.Validators,<br />            target.Validators);<br />    }<br /><br />    private ValidatorMerger CreateValidatorMerger()<br />    {<br />        return new ValidatorMerger(this.SourceSettings, this);<br />    }<br />}<br /><br />internal class ValidatorMerger<br />{<br />    private readonly IMerger parent;<br />    private readonly ValidationSettings settings;<br /><br />    public ValidatorMerger(ValidationSettings settings, IMerger parent)<br />    {<br />        this.parent = parent;<br />        this.settings = settings;<br />    }<br /><br />    public void MergeValidatorsInto(<br />        ValidatorDataCollection sourceValidators,<br />        ValidatorDataCollection targetValidators)<br />    {<br />        foreach (var sourceValidator in sourceValidators)<br />        {<br />            var targetValidator =<br />                targetValidators.Get(sourceValidator.Name);<br /><br />            if (targetValidator != null)<br />            {<br />                this.CreateValidatorMerger().MergeInto(targetValidator);<br />            }<br />            else<br />            {<br />                targetValidator = Copier.MakeCopy(sourceValidator);<br />                targetValidators.Add(targetValidator);<br />            }<br />        }<br />    }<br /><br />    public void MergeInto(ValidatorData target)<br />    {<br />        string parentsInformation =<br />            this.GetValidatorParentsInformation();<br /><br />        throw new ConfigurationErrorsException(String.Format(<br />            CultureInfo.InvariantCulture,<br />            &quot;The configuration file {0} contains a {1} &quot; +<br />            &quot;with name '{2}' that already is defined in &quot; +<br />            &quot;configuration {3}. {4}&quot;,<br />            this.settings.ElementInformation.Source,<br />            target.Type.Name, target.Name,<br />            target.ElementInformation.Source,<br />            parentsInformation));<br />    }<br /><br />    private string GetValidatorParentsInformation()<br />    {<br />        var parentsDescription =<br />            from parent in this.GetParents()<br />            select string.Format(CultureInfo.InvariantCulture,<br />            &quot;{0} '{1}'&quot;, parent.TypeName, parent.Name);<br /><br />        return string.Format(CultureInfo.InvariantCulture,<br />            &quot;The validator is defined in {0}.&quot;,<br />            string.Join(&quot;, &quot;, parentsDescription.ToArray()));<br />    }<br /><br />    private IEnumerable&lt;IMerger&gt; GetParents()<br />    {<br />        var parent = this.parent;<br /><br />        while (parent != null)<br />        {<br />            yield return parent;<br />            parent = parent.Parent;<br />        }<br />    }<br /><br />    private ValidatorMerger CreateValidatorMerger()<br />    {<br />        return new ValidatorMerger(this.settings, this.parent);<br />    }<br />}<br /><br />internal static class Copier<br />{<br />    public static ValidationSettings MakeCopy(<br />        ValidationSettings source)<br />    {<br />        var copy = new ValidationSettings();<br /><br />        foreach (var sourceType in source.Types)<br />        {<br />            copy.Types.Add(Copier.MakeCopy(sourceType));<br />        }<br /><br />        return copy;<br />    }<br /><br />    public static ValidatedTypeReference MakeCopy(<br />        ValidatedTypeReference source)<br />    {<br />        var target = new ValidatedTypeReference()<br />        {<br />            AssemblyName = source.AssemblyName,<br />            DefaultRuleset = source.DefaultRuleset,<br />            Name = source.Name,<br />        };<br />        <br />        foreach (var sourceRuleset in source.Rulesets)<br />        {<br />            target.Rulesets.Add(Copier.MakeCopy(sourceRuleset));<br />        }<br /><br />        return target;<br />    }<br /><br />    public static ValidationRulesetData MakeCopy(<br />        ValidationRulesetData source)<br />    {<br />        var target = new ValidationRulesetData(source.Name);<br /><br />        Copier.CopyCollection(source.Fields, target.Fields);<br />        Copier.CopyCollection(source.Methods, target.Methods);<br />        Copier.CopyCollection(source.Properties, target.Properties);<br />        Copier.CopyValidators(source.Validators, target.Validators);<br /><br />        return target;<br />    }<br /><br />    public static TMember MakeCopy&lt;TMember&gt;(TMember sourceMember)<br />        where TMember : ValidatedMemberReference, new()<br />    {<br />        var target = new TMember();<br /><br />        target.Name = sourceMember.Name;<br /><br />        foreach (var sourceValidator in sourceMember.Validators)<br />        {<br />            target.Validators.Add(Copier.MakeCopy(sourceValidator));<br />        }<br /><br />        return target;<br />    }<br /><br />    public static ValidatorData MakeCopy(ValidatorData source)<br />    {<br />        // A validator is considered readonly, <br />        // we can simply use the reference.<br />        return source;<br />    }<br /><br />    private static void CopyCollection&lt;TMember&gt;(<br />        NamedElementCollection&lt;TMember&gt; sourceCollection,<br />        NamedElementCollection&lt;TMember&gt; targetCollection)<br />        where TMember : ValidatedMemberReference, new()<br />    {<br />        foreach (var sourceElement in sourceCollection)<br />        {<br />            targetCollection.Add(Copier.MakeCopy(sourceElement));<br />        }<br />    }<br /><br />    private static void CopyValidators(<br />        ValidatorDataCollection sourceValidators,<br />        ValidatorDataCollection targetValidators)<br />    {<br />        foreach (var sourceValidator in sourceValidators)<br />        {<br />            targetValidators.Add(Copier.MakeCopy(sourceValidator));<br />        }<br />    }<br />}<br /></pre>
		]]></content>
		<author>
			<name>Steven</name>
		</author>
	</entry>
	
	
	
	<entry>
		<title>Printer Jam</title>
		<link rel="alternate" type="text/html" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=71" />
		<updated>2010-02-19T12:53:00+02:00</updated>
		<published>2010-02-19T11:07:00+02:00</published>
		<id>tag:pivotpowered,2012:NETJunkie.71</id>
		<link rel="related" type="text/html" href=""  />
		<summary type="text">The last couple of days I've been having a Printer Jam on my way to work.</summary>
        <content type="html" xml:lang="en" xml:base="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=71"><![CDATA[
                The last couple of days I've been having a Printer Jam on my way to work.<p>Okay, this is totally unrelated to technology; I've bought <a rel="external" href="http://shop.hospitalrecords.com/product/nhs148/" title="Mistabishi - Drop">this fantastic Drum &amp; Bass album</a> recently and play it when cycling to work in the morning. One of the tracks on this CD is called Printer Jam (see fantastic video <a rel="external" href="http://www.youtube.com/watch?v=is-HVxmUELQ" title="YouTube - Mistabishi - Printer Jam">here</a> on YourTube).</p><p>The track saves me from using caffeine to get running in the morning.<br /><br />Two thumbs up for <a rel="external" href="http://www.hospitalrecords.com/artists/mistabishi/" title="Mistabishi">Drum &amp; Bass DJ Mistabishi</a>.</p>
		]]></content>
		<author>
			<name>Steven</name>
		</author>
	</entry>
	
	
	
	<entry>
		<title>Simple Service Locator - The easiest Inversion of Control framework in town</title>
		<link rel="alternate" type="text/html" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=70" />
		<updated>2011-04-01T13:27:00+02:00</updated>
		<published>2010-01-06T17:35:00+02:00</published>
		<id>tag:pivotpowered,2012:NETJunkie.70</id>
		<link rel="related" type="text/html" href=""  />
		<summary type="text">The Simple Service Locator is an easy-to-use Inversion of Control library that is a complete implementation of the Common Service Locator interface. It solely supports code-based configuration and is an ideal starting point for developers unfamiliar with larger IoC / DI libraries</summary>
        <content type="html" xml:lang="en" xml:base="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=70"><![CDATA[
                The Simple Service Locator is an easy-to-use Inversion of Control library that is a complete implementation of the Common Service Locator interface. It solely supports code-based configuration and is an ideal starting point for developers unfamiliar with larger IoC / DI libraries<p style="border: 2px solid #00cc00; padding: 4px; background-color: #eeffee"><strong>Download:</strong> The Simple Service Locator library and source code can be downloaded from <a rel="external external" href="http://codeplex.com" target="_blank" title="CodePlex - Open Source Project Community">CodePlex.com</a>. Visit the homepage at <a rel="external external" href="http://simpleservicelocator.codeplex.com" target="_blank" title="Simple Service Locator - truly simple dependency injection">simpleservicelocator.codeplex.com</a> or go directly to the <a rel="external external" href="http://simpleservicelocator.codeplex.com/Release/ProjectReleases.aspx" target="_blank" title="Simple Service Locator - Downloads">Downloads</a> tab.</p> <p><img src="http://www.cuttingedge.it/blogs/steven/images/di.jpg" style="float:right;margin-left:10px;margin-bottom:5px;border:1px solid" title="Injection of uuhhm.. dependencies" alt="Injection of uuhhm.. dependencies" class="pivot-image" />Many development teams I help have legacy code bases with little or no unit tests. As you can imagine, the complexity makes it hard to add new features and fix existing bugs. Changing the course is often not easy, because the developers need to learn a whole new back of tricks. One of those tricks is unit testing and to me inextricably connected with that is <a rel="external" href="http://en.wikipedia.org/wiki/Dependency_injection" title="Wikipedia - Dependency injection">dependency injection</a>.</p><p>To get teams on the road quickly I often want to do the simplest thing that could possibly work. For that reason I've been annoyed with the complexity of the <a rel="external" href="http://www.hanselman.com/blog/ListOfNETDependencyInjectionContainersIOC.aspx" title="Scott Hanselman - List of .NET Dependency Injection Containers (IOC)">popular inversion of control frameworks</a>. The concepts of <a rel="external" href="http://en.wikipedia.org/wiki/Inversion_of_control" title="Wikipedia - Inversion of control">inversion of control</a> (IoC), dependency injection and good <a rel="external" href="http://weblogs.asp.net/rosherove/archive/2009/12/31/rtm-ready-tests.aspx" title="readable, maintainable and trust-worthy unit tests">RTM unit tests</a> are by itself hard enough to gasp for many developers. Learning to work with and configure several different frameworks (such as logging, validation, O/RM, and dependency injection) at the same time makes it even harder.</p><p>For this reason I started the <a rel="external" href="http://simpleservicelocator.codeplex.com/" title="Simple Service Locator - truly easy dependency injection">Simple Service Locator</a> project on <a rel="external" href="http://www.codeplex.com" title="Microsoft's CodePlex">CodePlex</a>. It&rsquo;s a (yet another) IoC library for .NET. Key features are its simplicity and it being an implementation of the <a rel="external" href="http://commonservicelocator.codeplex.com" title="Common Service Locator - an abstraction over IoC containers">Common Service Locator</a> interface. This makes it especially useful for development teams unfamiliar with one of the existing IoC frameworks. Development teams can start using the <em>Simple Service Locator</em> and replace it with a more feature-rich IoC framework later on when needed, without having to alter any production code. For the lifetime of many projects however, I expect the <em>Simple Service Locator</em> just to be sufficient.</p><p><em>Simple Service Locator</em> is an implementation of the <em>Common Service Locator</em> (CSL) interface and is not meant to be used without it. Therefore production code should only call CSL's <span class="type">ServiceLocator</span> facade, as is shown in the following example:</p><pre class="cs" language="csharp" customtypes="IWeapon ServiceLocator" customvaluetypes="PutYourCustomValueTypesHere">IWeapon weapon = ServiceLocator.Current.GetInstance&lt;IWeapon&gt;();</pre><p>Configuring the <em>Simple Service Locator</em> is done in the startup path of the application, as can be seen below. In this example you see how the <em>Simple Service Locator</em> is configured in the Application_Start event of the global.asax of a ASP.NET web application.</p><pre class="cs" language="csharp" customtypes="Global HttpApplication SimpleServiceLocator Warrior IWeapon Katana ServiceLocator" customvaluetypes="PutYourCustomValueTypesHere">using System;<br />using CuttingEdge.ServiceLocation;<br />using Microsoft.Practices.ServiceLocation;<br /><br />public class Global : System.Web.HttpApplication<br />{<br />    protected void Application_Start(object sender, EventArgs e)<br />    {<br />        // 1. Create a new Simple Service Locator container<br />        var container = new SimpleServiceLocator();<br /><br />        // 2. Configure the container<br /><br />        // Register a delegate that will create a new<br />        // instance on each call to GetInstance&lt;Warrior&gt;.<br />        container.Register&lt;Warrior&gt;(() =&gt;<br />            {<br />                var weapon = container.GetInstance&lt;IWeapon&gt;();<br />                return new Samurai(weapon);<br />            });<br /><br />        // Register a single object instance that always<br />        // be returned (must be thread-safe).<br />        container.RegisterSingle&lt;IWeapon&gt;(new Katana());<br /><br />        // 3. Register the container to the Common Locator<br />        ServiceLocator.SetLocatorProvider(() =&gt; container);<br />    }<br />}</pre><p>Please visit the <a rel="external" href="http://simpleservicelocator.codeplex.com/" title="Simple Service Locator - truly simple dependency injection">Simple Service Locator home page</a> to see more code examples.</p><p>The project is currently in beta, which means your feedback is very welcome. What do you think of the current API? Can we make it even simpler? Do you miss anything? I like to know.</p><p>Cheers.</p>
		]]></content>
		<author>
			<name>Steven</name>
		</author>
	</entry>
	
	
	
	<entry>
		<title>CuttingEdge.Conditions in MSDN Magazine Toolbox column</title>
		<link rel="alternate" type="text/html" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=68" />
		<updated>2011-04-01T13:37:00+02:00</updated>
		<published>2009-11-10T22:14:00+02:00</published>
		<id>tag:pivotpowered,2012:NETJunkie.68</id>
		<link rel="related" type="text/html" href=""  />
		<summary type="text">In the November 2009 issue of his MSDN Magazine Toolbox column, Scott Mitchell writes about CuttingEdge.Conditions.</summary>
        <content type="html" xml:lang="en" xml:base="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=68"><![CDATA[
                In the <a rel="external" href="http://msdn.microsoft.com/en-us/magazine/ee335714.aspx" title="MSDN Magazine - November 2009 - Database Documentation, API for Pre- and Post-Conditions, Blogs and More">November 2009 issue</a> of his MSDN Magazine Toolbox column, <a rel="external" href="http://scottonwriting.net" title="Scott on Writing">Scott Mitchell</a> writes about <a rel="external" href="http://conditions.codeplex.com/" title="CuttingEdge.Conditions @ CodePlex">CuttingEdge.Conditions</a>.<img src="http://www.cuttingedge.it/blogs/steven/images/msdn.jpg" style="float:left;margin-right:10px;margin-bottom:5px;border:0px solid" title="" alt="" class="pivot-image" /><img src="http://www.cuttingedge.it/blogs/steven/images/conditions.jpg" style="float:right;margin-left:10px;margin-bottom:5px;border:1px solid" title="" alt="" class="pivot-image" />Of course I think this is great news. <a rel="external" href="http://msdn.microsoft.com/en-us/magazine/default.aspx" title="MSDN Magazine">MSDN Magazine</a> has a large audience and I hope this increases the interest in my library, because this can lead to an larger user community and an increase of the amount of feedback on Conditions which will further increase the quality of it.<br /><br />While I am very pleased with this advertisement, I regret the fact that Scott uses the old extension method syntax in his Toolbox column. A syntax where the <span class="code">Requires()</span> method is written as extension method (such as '<span class="code">a.Requires()</span>') isn't supported anymore (for reasons I explained <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=57" title=".NET Junkie - Controversial change in CuttingEdge.Conditions">here</a>).<br /><br />While <a rel="external" href="http://scottonwriting.net/sowblog/posts/14022.aspx" title="Scott on Writing - November's Toolbox Column Now Online">promoting his Toolbox column</a> on his weblog on the other hand, Scott uses the supported syntax. That gives me the impression that he wrote the text for his Toolbox column some time ago.<br /><br />Nevertheless I&rsquo;m very pleased with Scott&rsquo;s review!
		]]></content>
		<author>
			<name>Steven</name>
		</author>
	</entry>
	
	
	
	<entry>
		<title>Vote for Visual Studio Text Editor Guidelines to Return</title>
		<link rel="alternate" type="text/html" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=67" />
		<updated>2009-11-04T15:36:00+02:00</updated>
		<published>2009-11-03T17:42:00+02:00</published>
		<id>tag:pivotpowered,2012:NETJunkie.67</id>
		<link rel="related" type="text/html" href=""  />
		<summary type="text">Visual Studio 2005 and 2008 contain a (not officially supported) feature that allows display of vertical guidelines in the (code) text editor. Visual Studio 2010 however, seems to completely miss this feature. I created a feature request on Microsoft Connect. Please help and vote for this feature to return.</summary>
        <content type="html" xml:lang="en" xml:base="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=67"><![CDATA[
                <p>Visual Studio 2005 and 2008 contain a (not officially supported) feature that allows display of vertical guidelines in the (code) text editor. Visual Studio 2010 however, seems to completely miss this feature. I created a feature request on Microsoft Connect. Please help and vote for this feature to return.</p><p>In Visual Studio 2005 and 2008 this feature is quite a hack actually, because a manual tweak in the Windows registry is needed. <a rel="external" href="http://blogs.msdn.com/saraford/default.aspx" title="Sara Ford's Weblog">Sara Ford</a> writes in <a rel="external" href="http://blogs.msdn.com/saraford/archive/2004/05/05/257953.aspx" title="Sara Ford's Weblog - Guidelines &ndash; a hidden feature for the Visual Studio Editor ">a hidden feature for the Visual Studio Editor</a> about how to configure this.</p><p style="text-align:center;"><img src="http://www.cuttingedge.it/blogs/steven/images/guidelines.jpg" style="border:0px solid" title="" alt="" class="pivot-image" /></p> I use this feature extensively to check to see whether I write my code conform the coding guidelines of the projects I participate in. Most of those projects define a rule that describes how long a line of code may be.</p><p>According to the following <a rel="external" href="https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=484758" title="Microsoft Connect - Guidelines setting for Text Editor is missing in Visual Studio 2010">bug report</a> the feature is removed from Visual Studio 2010. Not only do I want this feature back, I like to see it supported and improved! </p><p>The thing is that VS 2005 and 2008 don't allow the guidelines to be specified on a per C# project basis. This is a problem when a single developer is working on multiple projects (with different line length rules) on a single machine.</p><p><strong>For this reason I opened the following feature request on the Microsoft Connect site: <a rel="external" href="https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=507891" title="Microsoft Connect - Allow texteditor guidelines to be specified in project settings">Allow text editor guidelines to be specified in project settings</a>.</strong></p><p>Please help to get this feature back in Visual Studio 2010 and get it improved by voting on this feature request. </p><p>Thanks.</p>
		]]></content>
		<author>
			<name>Steven</name>
		</author>
	</entry>
	
	
	
	<entry>
		<title>Sorting entities with the EntitySorter</title>
		<link rel="alternate" type="text/html" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=66" />
		<updated>2009-11-11T16:22:00+02:00</updated>
		<published>2009-10-25T21:28:00+02:00</published>
		<id>tag:pivotpowered,2012:NETJunkie.66</id>
		<link rel="related" type="text/html" href=""  />
		<summary type="text">This article describes the EntitySorter<T> class. It's a nifty little thing that allows the presentation layer to instruct the service layer how collections should be returned.</summary>
        <content type="html" xml:lang="en" xml:base="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=66"><![CDATA[
                This article describes the EntitySorter&lt;T&gt; class. It's a nifty little thing that allows the presentation layer to instruct the service layer how collections should be returned.<p>About a year ago I was, just like everybody else, trying to figure out how to fit Entity Framework and LINQ to SQL into architectural perspective. Especially within the context of ASP.NET applications. One of the things I figured out pretty quickly was the following: The LINQ to SQL <span class="type">DataContext</span> and Entity Framework <span class="type">ObjectContext</span> classes should not outlive a call to the service layer. There are several opinions about this, but for me this rule is very important. The presentation layer shouldn't know anything about connections and transactions. Next to that, the service layer should have full control over how and when there is communication with the database. Leaking the context classes out of the service layer is an architectural smell.</p><p>Consequence of this architectural rule is that the service layer should not return objects that implement <span class="type">IQueryable</span>. Neither should you return entities with lazy loading capacities, because this would allow the presentation layer to make extra calls to the database, without the service layer knowing this (and it needs for the context to stay alive).</p><p>The approach I take is rather radical. I make sure that <span class="type">DataContext</span> and <span class="type">ObjectContext</span> classes are disposed by the layer that creates them (as you should do with all <span class="type">IDisposable</span> objects) and return <a rel="external" href="http://martinfowler.com/eaaCatalog/dataTransferObject.html" title="Martin Fowler - Data Transfer Object">Data Transfer Objects</a> often.</p><p>This subject deserves a whole post on it's own, but this architectural rule has some consequences on your design. When you're not allowed to return <span class="type">IQueryable</span> objects from the service layer, you are faced with some challenges. One of those challenges is sorting.</p><p>Many user interfaces allow the user to sort results. While the presentation layer can sort a collection that's returned from the service layer, this could cause a severe performance problem, when working with paged result sets.</p><p>To solve this problem, the presentation layer should be able to instruct the service layer how to sort a requested set of results. A nice way to achieve this is by using a construct that's similar to <a rel="external" href="http://martinfowler.com/eaaCatalog/queryObject.html" title="Martin Fowler - Query Object">Fowler's Query Object</a>.</p><p>To achieve this, let's define an interface that allows sorting of collections:</p><pre class="cs" language="csharp" customtypes="IQueryable IOrderedQueryable IEntitySorter Person Condition EntitySorter PersonServices" customvaluetypes="SortDirection">public interface IEntitySorter&lt;TEntity&gt;<br />{<br />    IOrderedQueryable&lt;TEntity&gt; Sort(IQueryable&lt;TEntity&gt; collection);<br />}</pre><p>Implementations of this interface can be supplied by the presentation layer to methods in the service layer to allow sorting. Below is an example of the use of this 'sort object' in the service layer:</p><pre class="cs" language="csharp" customtypes="IQueryable IOrderedQueryable IEntitySorter Person Condition EntitySorter PersonServices" customvaluetypes="SortDirection">public static Person[] GetAllPersons(IEntitySorter&lt;Person&gt; sorter)<br />{<br />    Condition.Requires(sorter, &quot;sorter&quot;).IsNotNull();<br /><br />    using (var db = ContextFactory.CreateContext())<br />    {<br />        IOrderedQueryable&lt;Person&gt; sortedList =<br />            sorter.Sort(db.Persons);<br /><br />        return sortedList.ToArray();<br />    }<br />}</pre><p>Note that this interface processes an <span class="type">IQueryable</span> and returns an <span class="type">IOrderedQueryable</span>. Because <span class="type">IQueryable</span> uses expression trees, frameworks like LINQ to SQL and Entity Framework can parse it. This allows sorting to be executed in the database. The place where this is (usually) done best.</p><p>Now let's think about how the presentation layer code should look. This layer shouldn't have to define new implementations of this interface for each and every call to the service layer. We want to have some sort of facade that allows us to create new instances easily. I'm thinking about code like this:</p><pre class="cs" language="csharp" customtypes="IQueryable IOrderedQueryable IEntitySorter Person Condition EntitySorter PersonServices" customvaluetypes="SortDirection">var sorter = EntitySorter&lt;Person&gt;.OrderBy(p =&gt; p.Id);<br />var persons = PersonServices.GetAllPersons(sorter);</pre><p>And I'd like to be able to sort in descending order:</p><pre class="cs" language="csharp" customtypes="IQueryable IOrderedQueryable IEntitySorter Person Condition EntitySorter PersonServices" customvaluetypes="SortDirection">var sorter = EntitySorter&lt;Person&gt;.OrderByDescending(p =&gt; p.Id); <br /></pre><p>And I'd like to be able to sort on multiple things, like this:</p><pre class="cs" language="csharp" customtypes="IQueryable IOrderedQueryable IEntitySorter Person Condition EntitySorter PersonServices" customvaluetypes="SortDirection">var sorter = EntitySorter&lt;Person&gt;<br />    .OrderBy(p =&gt; p.Name)<br />    .ThenBy(p =&gt; p.Id);</pre><p>And it should be easy to create a new instance, based on the name of a property, simply because much of ASP.NET's infrastructure is based on strings. Controls like GridView supply string based property names. Therefore, the API should allow the following syntax:</p><pre class="cs" language="csharp" customtypes="IQueryable IOrderedQueryable IEntitySorter Person Condition EntitySorter PersonServices" customvaluetypes="SortDirection">var sorter = EntitySorter&lt;Person&gt;.OrderBy(&quot;Name&quot;);</pre><p>And it must be possible to sort on properties in related objects, like this:</p><pre class="cs" language="csharp" customtypes="IQueryable IOrderedQueryable IEntitySorter Person Condition EntitySorter PersonServices" customvaluetypes="SortDirection">var sorter1 = EntitySorter&lt;Person&gt;.OrderBy(p =&gt; p.Address.City);<br />var sorter2 = EntitySorter&lt;Person&gt;.OrderBy(&quot;Address.City&quot;);</pre><p>And while we're add it, it would be cool if we could use LINQ syntax to define a new sorter:</p><pre class="cs" language="csharp" customtypes="IQueryable IOrderedQueryable IEntitySorter Person Condition EntitySorter PersonServices" customvaluetypes="SortDirection">IEntitySorter&lt;Person&gt; sorter =<br />    from person in EntitySorter&lt;Person&gt;.AsQueryable()<br />    orderby person.Name descending, person.Id<br />    select person;</pre><p>I think this is a nice API that would work. Now let's build it!</p><pre class="cs" language="csharp" customtypes="IQueryable IOrderedQueryable IEntitySorter Person Condition EntitySorter PersonServices EmptyEntitySorter Expression OrderBySorter EntitySorterBuilder ThenBySorter" customvaluetypes="SortDirection">internal enum SortDirection<br />{<br />    Ascending,<br />    Descending<br />}<br /><br />public static class EntitySorter&lt;T&gt;<br />{<br />    public static IEntitySorter&lt;T&gt; AsQueryable()<br />    {<br />        return new EmptyEntitySorter();<br />    }<br /><br />    public static IEntitySorter&lt;T&gt; OrderBy&lt;TKey&gt;(<br />        Expression&lt;Func&lt;T, TKey&gt;&gt; keySelector)<br />    {<br />        return new OrderBySorter&lt;T, TKey&gt;(keySelector,<br />            SortDirection.Ascending);<br />    }<br /><br />    public static IEntitySorter&lt;T&gt; OrderByDescending&lt;TKey&gt;(<br />        Expression&lt;Func&lt;T, TKey&gt;&gt; keySelector)<br />    {<br />        return new OrderBySorter&lt;T, TKey&gt;(keySelector,<br />            SortDirection.Descending);<br />    }<br /><br />    public static IEntitySorter&lt;T&gt; OrderBy(string propertyName)<br />    {<br />        var builder = new EntitySorterBuilder&lt;T&gt;(propertyName);<br /><br />        builder.Direction = SortDirection.Ascending;<br /><br />        return builder.BuildOrderByEntitySorter();<br />    }<br /><br />    public static IEntitySorter&lt;T&gt; OrderByDescending(<br />        string propertyName)<br />    {<br />        var builder = new EntitySorterBuilder&lt;T&gt;(propertyName);<br /><br />        builder.Direction = SortDirection.Descending;<br /><br />        return builder.BuildOrderByEntitySorter();<br />    }<br /><br />    private sealed class EmptyEntitySorter : IEntitySorter&lt;T&gt;<br />    {<br />        public IOrderedQueryable&lt;T&gt; Sort(<br />            IQueryable&lt;T&gt; collection)<br />        {<br />            string exceptionMessage = &quot;OrderBy should be called.&quot;;<br /><br />            throw new InvalidOperationException(exceptionMessage);<br />        }<br />    }<br />}</pre><p>The snippet above shows the implementation of the <span class="type">EntitySorter</span><span class="code">&lt;T&gt;</span> facade. As you might have noticed, the class only defines the <span class="code">OrderBy</span> and <span class="code">OrderByDescending</span> methods. <span class="code">ThenBy</span> and <span class="code">ThenByDescending</span> aren't specified here. It makes sense when you think about this, because you always chain the <span class="code">ThenBy</span> call after an <span class="code">OrderBy</span> call, thus <span class="code">ThenBy</span> should be implemented as instance method, or as we'll see shortly, as extension method.</p><p>The next snippet shows the extension methods:</p><pre class="cs" language="csharp" customtypes="IQueryable IOrderedQueryable IEntitySorter Person Condition EntitySorter PersonServices Expression" customvaluetypes="SortDirection">public static class EntitySorterExtensions<br />{<br />    public static IEntitySorter&lt;T&gt; OrderBy&lt;T, TKey&gt;(<br />        this IEntitySorter&lt;T&gt; sorter,<br />        Expression&lt;Func&lt;T, TKey&gt;&gt; keySelector)<br />    {<br />        return EntitySorter&lt;T&gt;.OrderBy(keySelector);<br />    }<br /><br />    public static IEntitySorter&lt;T&gt; OrderByDescending&lt;T, TKey&gt;(<br />        this IEntitySorter&lt;T&gt; sorter,<br />        Expression&lt;Func&lt;T, TKey&gt;&gt; keySelector)<br />    {<br />        return EntitySorter&lt;T&gt;.OrderByDescending(keySelector);<br />    }<br /><br />    public static IEntitySorter&lt;T&gt; ThenBy&lt;T, TKey&gt;(<br />        this IEntitySorter&lt;T&gt; sorter,<br />        Expression&lt;Func&lt;T, TKey&gt;&gt; keySelector)<br />    {<br />        return new ThenBySorter&lt;T, TKey&gt;(sorter,<br />            keySelector, SortDirection.Ascending);<br />    }<br /><br />    public static IEntitySorter&lt;T&gt; ThenByDescending&lt;T, TKey&gt;(<br />        this IEntitySorter&lt;T&gt; sorter,<br />        Expression&lt;Func&lt;T, TKey&gt;&gt; keySelector)<br />    {<br />        return new ThenBySorter&lt;T, TKey&gt;(sorter,<br />            keySelector, SortDirection.Descending);<br />    }<br /><br />    public static IEntitySorter&lt;T&gt; ThenBy&lt;T&gt;(<br />        this IEntitySorter&lt;T&gt; sorter, string propertyName)<br />    {<br />        var builder = new EntitySorterBuilder&lt;T&gt;(propertyName);<br /><br />        builder.Direction = SortDirection.Ascending;<br /><br />        return builder.BuildThenByEntitySorter(sorter);<br />    }<br /><br />    public static IEntitySorter&lt;T&gt; ThenByDescending&lt;T&gt;(<br />        this IEntitySorter&lt;T&gt; sorter, string propertyName)<br />    {<br />        var builder = new EntitySorterBuilder&lt;T&gt;(propertyName);<br /><br />        builder.Direction = SortDirection.Descending;<br /><br />        return builder.BuildThenByEntitySorter(sorter);<br />    }<br />}</pre><p>Again no rocket science. Some things to note is that also the <span class="code">OrderBy</span> and <span class="code">OrderByDescending</span> (that we saw in the <span class="type">EntitySorter</span><span class="code">&lt;T&gt;</span> class) are defined here. Specifying them as extension methods allows us to write LINQ queries. You can see that the implementation simply calls back to the <span class="type">EntitySorter</span><span class="code">&lt;T&gt;.OrderBy</span> method.</p><p>The classes returned from these methods are internal implementations named <span class="type">OrderBySorter</span><span class="code">&lt;T, TKey&gt;</span> and <span class="type">ThenBySorter</span><span class="code">&lt;T, TKey&gt;</span>. The implementations are rather straightforward. On creation, a key selector (a lambda) and a sorting direction are supplied. Their <span class="code">Sort</span> method transforms the supplied collection to a ordered collection. Here are the implementations:</p><pre class="cs" language="csharp" customtypes="IQueryable IOrderedQueryable IEntitySorter Person Condition EntitySorter PersonServices OrderBySorter ThenBySorter Expression Queryable" customvaluetypes="SortDirection">internal class OrderBySorter&lt;T, TKey&gt; : IEntitySorter&lt;T&gt;<br />{<br />    private readonly Expression&lt;Func&lt;T, TKey&gt;&gt; keySelector;<br />    private readonly SortDirection direction;<br /><br />    public OrderBySorter(Expression&lt;Func&lt;T, TKey&gt;&gt; selector,<br />        SortDirection direction)<br />    {<br />        this.keySelector = selector;<br />        this.direction = direction;<br />    }<br /><br />    public IOrderedQueryable&lt;T&gt; Sort(IQueryable&lt;T&gt; col)<br />    {<br />        if (this.direction == SortDirection.Ascending)<br />        {<br />            return Queryable.OrderBy(col, this.keySelector);<br />        }<br />        else<br />        {<br />            return Queryable.OrderByDescending(col,<br />                this.keySelector);<br />        }<br />    }<br />}<br /><br />internal sealed class ThenBySorter&lt;T, TKey&gt; : IEntitySorter&lt;T&gt;<br />{<br />    private readonly IEntitySorter&lt;T&gt; baseSorter;<br />    private readonly Expression&lt;Func&lt;T, TKey&gt;&gt; keySelector;<br />    private readonly SortDirection direction;<br /><br />    public ThenBySorter(IEntitySorter&lt;T&gt; baseSorter,<br />        Expression&lt;Func&lt;T, TKey&gt;&gt; selector, SortDirection direction)<br />    {<br />        this.baseSorter = baseSorter;<br />        this.keySelector = selector;<br />        this.direction = direction;<br />    }<br /><br />    public IOrderedQueryable&lt;T&gt; Sort(IQueryable&lt;T&gt; col)<br />    {<br />        var sorted = this.baseSorter.Sort(col);<br /><br />        if (this.direction == SortDirection.Ascending)<br />        {<br />            return Queryable.ThenBy(sorted, this.keySelector);<br />        }<br />        else<br />        {<br />            return Queryable.ThenByDescending(sorted,<br />                this.keySelector);<br />        }<br />    }<br />}</pre><p>As you can see the two classes simply use the .NET framework's <span class="type">Queryable</span> class to sort the supplied collection. It couldn't be easier.</p><p>Until now, the code was pretty straightforward. However, the API allows sorting based on the name of the property. I extracted this complicated logic to another class: the <span class="type">EntitySorterBuilder</span><span class="code">&lt;T&gt;</span>. As seen above, the usage of the <span class="type">EntitySorterBuilder</span><span class="code">&lt;T&gt;</span> is used as follows:</p><pre class="cs" language="csharp" customtypes="IQueryable IOrderedQueryable IEntitySorter Person Condition EntitySorter PersonServices EntitySorterBuilder" customvaluetypes="SortDirection">var builder = new EntitySorterBuilder&lt;T&gt;(propertyName);<br /><br />builder.Direction = SortDirection.Descending;<br /><br />IEntitySorter&lt;T&gt; sorter = builder.BuildOrderByEntitySorter();</pre>  <p>The builder creates <span class="type">OrderBySorter</span><span class="code">&lt;T, TKey&gt;</span> and <span class="type">ThenBySorter</span><span class="code">&lt;T, TKey&gt;</span> implementations, using some heavy reflection. Here's the code:</p><pre class="cs" language="csharp" customtypes="IQueryable IOrderedQueryable IEntitySorter Person Condition EntitySorter PersonServices EmptyEntitySorter Expression OrderBySorter EntitySorterBuilder ThenBySorter LambdaExpression MethodInfo ILambdaBuilder LambdaBuilder PropertyInfo ParameterExpression Expression" customvaluetypes="SortDirection BindingFlags">internal class EntitySorterBuilder&lt;T&gt;<br />{<br />    private readonly Type keyType;<br />    private readonly LambdaExpression keySelector;<br /><br />    public EntitySorterBuilder(string propertyName)<br />    {<br />        List&lt;MethodInfo&gt; propertyAccessors =<br />            GetPropertyAccessors(propertyName);<br /><br />        this.keyType = propertyAccessors.Last().ReturnType;<br /><br />        ILambdaBuilder builder = CreateLambdaBuilder(keyType);<br /><br />        this.keySelector =<br />            builder.BuildLambda(propertyAccessors);<br />    }<br /><br />    private interface ILambdaBuilder<br />    {<br />        LambdaExpression BuildLambda(<br />            IEnumerable&lt;MethodInfo&gt; propertyAccessors);<br />    }<br /><br />    public SortDirection Direction { get; set; }<br /><br />    public IEntitySorter&lt;T&gt; BuildOrderByEntitySorter()<br />    {<br />        Type[] typeArgs = new[] { typeof(T), this.keyType };<br /><br />        Type sortType =<br />            typeof(OrderBySorter&lt;,&gt;).MakeGenericType(typeArgs);<br /><br />        return (IEntitySorter&lt;T&gt;)Activator.CreateInstance(sortType,<br />            this.keySelector, this.Direction);<br />    }<br /><br />    public IEntitySorter&lt;T&gt; BuildThenByEntitySorter(<br />        IEntitySorter&lt;T&gt; baseSorter)<br />    {<br />        Type[] typeArgs = new[] { typeof(T), this.keyType };<br /><br />        Type sortType =<br />            typeof(ThenBySorter&lt;,&gt;).MakeGenericType(typeArgs);<br /><br />        return (IEntitySorter&lt;T&gt;)Activator.CreateInstance(sortType,<br />            baseSorter, this.keySelector, this.Direction);<br />    }<br /><br />    private static ILambdaBuilder CreateLambdaBuilder(Type keyType)<br />    {<br />        Type[] typeArgs = new[] { typeof(T), keyType };<br /><br />        Type builderType =<br />            typeof(LambdaBuilder&lt;&gt;).MakeGenericType(typeArgs);<br /><br />        return (ILambdaBuilder)Activator.CreateInstance(builderType);<br />    }<br /><br />    private static List&lt;MethodInfo&gt; GetPropertyAccessors(<br />        string propertyName)<br />    {<br />        try<br />        {<br />            return GetPropertyAccessorsFromChain(propertyName);<br />        }<br />        catch (InvalidOperationException ex)<br />        {<br />            string message = propertyName +<br />                &quot; could not be parsed. &quot; + ex.Message;<br /><br />            // We throw a more expressive exception at this level.<br />            throw new ArgumentException(message, &quot;propertyName&quot;);<br />        }<br />    }<br /><br />    private static List&lt;MethodInfo&gt; GetPropertyAccessorsFromChain(<br />        string propertyNameChain)<br />    {<br />        var propertyAccessors = new List&lt;MethodInfo&gt;();<br /><br />        var declaringType = typeof(T);<br /><br />        foreach (string name in propertyNameChain.Split('.'))<br />        {<br />            var accessor = GetPropertyAccessor(declaringType, name);<br /><br />            propertyAccessors.Add(accessor);<br /><br />            declaringType = accessor.ReturnType;<br />        }<br /><br />        return propertyAccessors;<br />    }<br /><br />    private static MethodInfo GetPropertyAccessor(Type declaringType,<br />        string propertyName)<br />    {<br />        var prop = GetPropertyByName(declaringType, propertyName);<br /><br />        return GetPropertyGetter(prop);<br />    }<br /><br />    private static PropertyInfo GetPropertyByName(Type declaringType,<br />        string propertyName)<br />    {<br />        BindingFlags flags = BindingFlags.IgnoreCase |<br />            BindingFlags.Instance | BindingFlags.Public;<br /><br />        var prop = declaringType.GetProperty(propertyName, flags);<br /><br />        if (prop == null)<br />        {<br />            string exceptionMessage = string.Format(<br />                &quot;{0} does not contain a property named '{1}'.&quot;,<br />                declaringType, propertyName);<br /><br />            throw new InvalidOperationException(exceptionMessage);<br />        }<br /><br />        return prop;<br />    }<br /><br />    private static MethodInfo GetPropertyGetter(PropertyInfo property)<br />    {<br />        var propertyAccessor = property.GetGetMethod();<br /><br />        if (propertyAccessor == null)<br />        {<br />            string exceptionMessage = string.Format(<br />                &quot;The property '{1}' does not contain a getter.&quot;,<br />                property.Name);<br /><br />            throw new InvalidOperationException(exceptionMessage);<br />        }<br /><br />        return propertyAccessor;<br />    }<br /><br />    private sealed class LambdaBuilder&lt;TKey&gt; : ILambdaBuilder<br />    {<br />        public LambdaExpression BuildLambda(<br />            IEnumerable&lt;MethodInfo&gt; propertyAccessors)<br />        {<br />            ParameterExpression parameterExpression =<br />                Expression.Parameter(typeof(T), &quot;entity&quot;);<br /><br />            Expression propertyExpression = BuildPropertyExpression(<br />                propertyAccessors, parameterExpression);<br /><br />            return Expression.Lambda&lt;Func&lt;T, TKey&gt;&gt;(<br />                propertyExpression, new[] { parameterExpression });<br />        }<br /><br />        private static Expression BuildPropertyExpression(<br />            IEnumerable&lt;MethodInfo&gt; propertyAccessors,<br />            ParameterExpression parameterExpression)<br />        {<br />            Expression propertyExpression = null;<br /><br />            foreach (var propertyAccessor in propertyAccessors)<br />            {<br />                var innerExpression =<br />                    propertyExpression ?? parameterExpression;<br /><br />                propertyExpression = Expression.Property(<br />                    innerExpression, propertyAccessor);<br />            }<br /><br />            return propertyExpression;<br />        }<br />    }<br />}</pre><p>The <span class="type">EntitySorterBuilder</span><span class="code">&lt;T&gt;</span> does a few interesting things. First of all it creates a list of property accessors (getter methods), based on the property names. For instance, it creates a list of two getter methods when the following string is supplied: &quot;Address.City&quot;. Next it generates a lambda expression (the keySelector) based on the list of property accessors, in the following form: 'e =&gt; e.[Property1].[Property2]'). After that, it creates a new <span class="type">OrderBySorter</span><span class="code">&lt;T, TKey&gt;</span> or <span class="type">ThenBySorter</span><span class="code">&lt;T, TKey&gt;</span> with the generated lambda expression as constructor argument and returns it.</p><p>I hope this <span class="type">EntitySorter</span><span class="code">&lt;T&gt;</span> comes in handy to some of you. I has already served me well over the last year.</p><p>I just created an <a rel="external" href="http://servicelayerhelpers.codeplex.com" title="CuttingEdge.ServiceLayerHelpers @ CodePlex">CodePlex project</a> that contains the code shown above. The code on CodePlex has additional error checking, (xml) comments and more descriptive variable names. So don't copy-paste the code from this blog; just browse directly to the source code, by clicking <a rel="external" href="http://servicelayerhelpers.codeplex.com/SourceControl/changeset/view/34401#537056" title="CuttingEdge.ServiceLayerHelpers Source Code - EntitySorter&lt;TEntity&gt;">here</a>.</p><p>The project also contains an <span class="type">EntityFilter</span><span class="code">&lt;T&gt;</span> class (<a rel="external" href="http://servicelayerhelpers.codeplex.com/SourceControl/changeset/view/32810#537055" title="CuttingEdge.ServiceLayerHelpers Source Code - EntityFilter&lt;TEntity&gt;">here</a> the code) that allows filtering of collections. Just like the <span class="type">EntitySorter</span><span class="code">&lt;T&gt;</span> it allows creation using LINQ queries, like this:</p><pre class="cs" language="csharp" customtypes="IQueryable IOrderedQueryable IEntitySorter Person Condition EntitySorter PersonServices IEntityFilter EntityFilter" customvaluetypes="SortDirection">IEntityFilter&lt;Person&gt; entityFilter =<br />    from person in EntityFilter&lt;Person&gt;.AsQueryable()<br />    where person.Name.StartsWith(&quot;a&quot;)<br />    where person.Id &lt; 100<br />    select person;</pre><p>Happy sorting and filtering!</p>
		]]></content>
		<author>
			<name>Steven</name>
		</author>
	</entry>
	
	
	
	<entry>
		<title>Putting the Validation Application Block configuration in its own file</title>
		<link rel="alternate" type="text/html" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=65" />
		<updated>2010-02-14T22:36:00+02:00</updated>
		<published>2009-09-30T11:00:00+02:00</published>
		<id>tag:pivotpowered,2012:NETJunkie.65</id>
		<link rel="related" type="text/html" href=""  />
		<summary type="text">This article describes how to extract the validation configuration to its own file and allow this to also work with unit tests.</summary>
        <content type="html" xml:lang="en" xml:base="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=65"><![CDATA[
                This article describes how to extract the validation configuration to its own file and allow this to also work with unit tests.<p>The problem that you encounter pretty quickly when defining the VAB configuration in the normal web.config or app.config is that you need to have multiple copies of that configuration. You'll have at least two copies: one for your unit tests and one file for the application itself. At first this is a bit annoying, but it get's frustrating quickly after that. Later on it leads to errors, after someone on your team updated the unit test configuration, but forgot to update the application&rsquo;s configuration file.</p><p>Luckily the Enterprise Library allows you to choose alternative configuration files using the <a rel="external" href="http://msdn.microsoft.com/en-us/library/microsoft.practices.enterpriselibrary.common.configuration.iconfigurationsource%28BTS.10%29.aspx" title="MSDN - IConfigurationSource Interface">IConfigurationSource</a> interface. Later more on this, but first here is how you put the VAB configuration in it&rsquo;s own file:</p><p>Start by adding a new configuration file to on of your projects (most likely on of your business layer projects). After you created it, change the &quot;<em>Copy to Output Directory</em>&quot; property to &quot;<em>Copy if newer</em>&quot; by right-clicking on the file and choosing &lsquo;properties&rsquo;. This will enable the configuration file to be copied to the output directory, which isn't the default option.</p><p style="text-align:center;"><img src="http://www.cuttingedge.it/blogs/steven/images/validation_config_copy_to_output_directory.gif" style="border:0px solid" title="Copy to Output Directory" alt="Copy to Output Directory" class="pivot-image" /></p>
<p>After you've created the file you can simply add validation configuration the way you're used to using the Enterprise Library Configuration tool by right clicking on the configuration file and selecting &quot;Edit Enterprise Library Configuration&quot;, or by editing the file by hand.</p><p style="text-align:center;"><img src="http://www.cuttingedge.it/blogs/steven/images/validation_config_edit_enterprise_library_configuration.gif" style="border:0px solid" title="Edit Enterprise Library Configuration" alt="Edit Enterprise Library Configuration" class="pivot-image" /></p>
<p>Choosing &quot;Copy if newer&quot; for the validation configuration file has no effect in conjunction with Visual Studio Unit Tests. So the last step to take is to configure the test system to copy that file. The standard way to do this is by specifying the deployment items in the .testrunconfig file. You can do this by going to Test / Edit Test Run Configurations / Deployment. You can use the &quot;Add File...&quot; button to add the configuration file. The image below shows the deployment tab with a validation.config added.</p><p style="text-align:center;"><img src="http://www.cuttingedge.it/blogs/steven/images/validation_config_edit_test_run_configurations.gif" style="border:0px solid" title="Edit Test Run Configuration" alt="Edit Test Run Configuration" class="pivot-image" /></p>
<p><font color="#ff0000">&lt;UPDATE 2010-01-06&gt;</font><br />I forgot to mention how to exactly let the VAB know you replaced the configuration file.</p><p>You need to create an instance of a type implementing <span class="type">IConfigurationSource</span> and supply it to an overload of the <span class="type">ValidationFactory</span><span class="code">.CreateValidator</span> method. Using a configuration file named &quot;validation.config&quot;, the following code snippet can be used to create a <span class="type">Validator</span> based on that configuration:</p><pre class="cs" language="csharp" customtypes="IConfigurationSource FileConfigurationSource ValidationFactory" customvaluetypes="PutYourCustomValueTypesHere">string ruleSet = string.Empty;<br /><br />IConfigurationSource configurationSource =<br />    new FileConfigurationSource(&quot;validation.config&quot;);<br /><br />var validator = ValidationFactory.CreateValidator(type, ruleSet,<br />    configurationSource);</pre><p>Or when using the <span class="type">IEntityValidator</span> approach used in <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=64" title=".NET Junkie - Integrating Enterprise Library Validation Application Block With LINQ to SQL and Entity Framework Part 4: Using Metadata to Automate Validations">part 4</a> of my VAB series, the <span class="type">VABEntityValidator</span> would look like this:</p><pre class="cs" language="csharp" customtypes="VABEntityValidator IEntityValidator IConfigurationSource FileConfigurationSource ValidationResult Validator ValidationFactory" customvaluetypes="PutYourCustomValueTypesHere">using System;<br />using System.Collections.Generic;<br />using System.Linq;<br />using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;<br />using Microsoft.Practices.EnterpriseLibrary.Validation;<br /><br />sealed class VABEntityValidator : IEntityValidator<br />{<br />    private static IConfigurationSource ConfigurationSource =<br />       new FileConfigurationSource(&quot;validation.config&quot;);<br /><br />    public IEnumerable&lt;ValidationResult&gt; Validate(<br />        IEnumerable&lt;object&gt; entities)<br />    {<br />        return<br />            from entity in entities<br />            let type = entity.GetType()<br />            let validator = CreateValidator(type)<br />            let results = validator.Validate(entity)<br />            where !results.IsValid<br />            from result in results<br />            select result;<br />    }<br /><br />    private static Validator CreateValidator(Type type)<br />    {<br />        string ruleSet = string.Empty;<br /><br />        return ValidationFactory.CreateValidator(type, ruleSet,<br />            ConfigurationSource);<br />    }<br />}</pre><p><font color="#ff0000">&lt;/UPDATE&gt;</font> </p><p>Happy validating!</p>
		]]></content>
		<author>
			<name>Steven</name>
		</author>
	</entry>
	
	
	
	<entry>
		<title>Integrating Enterprise Library Validation Application Block With LINQ to SQL and Entity Framework Part 4: Using Metadata to Automate Validations</title>
		<link rel="alternate" type="text/html" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=64" />
		<updated>2011-08-05T10:35:00+02:00</updated>
		<published>2009-09-30T01:30:00+02:00</published>
		<id>tag:pivotpowered,2012:NETJunkie.64</id>
		<link rel="related" type="text/html" href=""  />
		<summary type="text">This article describes how to extract information from your generated LINQ to SQL entities to automate validations like maximum string length and disallowing null values.</summary>
        <content type="html" xml:lang="en" xml:base="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=64"><![CDATA[
                This article describes how to extract information from your generated LINQ to SQL entities to automate validations like maximum string length and disallowing null values.<p>In the <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/archive.php?c=Validation_Application_Block" title=".NET Junkie - Validation Application Block articles">previous parts</a> I wrote <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=46" title=".NET Junkie - Integrating Enterprise Library Validation Application Block With LINQ to SQL and Entity Framework Part 1: Basic Integration">how to integrate the Enterprise Library Validation Application Block with LINQ to SQL and Entity Framework projects</a>, <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=47" title=".NET Junkie - Integrating Enterprise Library Validation Application Block with LINQ to SQL and Entity Framework Part 2: Using context within custom validators.">enabled using the context within custom validators</a>, and wrote about <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=49" title=".NET Junkie - Integrating Enterprise Library Validation Application Block with LINQ to SQL and Entity Framework Part 3: The complexity of custom validators.">the complexity of custom validators</a>.</p><p>What's nice about LINQ to SQL (L2S) is that it adds all sort of metadata to the generated entities. Two things that come to mind are the maximum length of a database varchar column and whether a column can contain null values or not. While the Validation Application Block (VAB) has validators for these types of constraints (the <span class="type">NotNullValidator</span> and <span class="type">StringLengthValidator</span>), adding them manually can be cumbersome. Automating away boring labour is always welcome. In this article I'll show you how, while building on top of the solution presented in the previous articles.</p><p>Please note that Entity Framework (EF) adds much less metadata to its generated entities. With EF you still have to add those validations using the VAB configuration (also remember this when migrating from L2S to EF). However, the future of EF is bright and EF 4.0 will allow you to specify your own T4 template and therefore completely control the shape of the generated code.</p><p>In <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=46" title=".NET Junkie - NotNullValidator">part 1</a> and <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=47" title=".NET Junkie - Integrating Enterprise Library Validation Application Block with LINQ to SQL and Entity Framework Part 2: Using context within custom validators.">part 2</a> I defined the <span class="type">EntityValidator</span> class. Before writing the code for the validations, let's first change the <span class="type">EntityValidator</span> class, so it becomes more flexible for these and possible future changes:</p><pre class="cs" language="csharp" customtypes="Assembly ColumnAttribute ContextScope EntityValidator IEntityValidator LinqToSqlMaximumFieldLengthValidator LinqToSqlNullPropertyValidator VABEntityValidator  ValidationException ValidationFactory ValidationResult " customvaluetypes="PutYourCustomValueTypesHere">using System;<br />using System.Collections.Generic;<br />using System.Collections.ObjectModel;<br />using System.Linq;<br />using System.Reflection;<br /><br />interface IEntityValidator<br />{<br />    IEnumerable&lt;ValidationResult&gt;<br />        Validate(IEnumerable&lt;object&gt; entities);<br />}<br /><br />public static class EntityValidator<br />{<br />    private static readonly IEntityValidator[] Validators;<br /><br />    static EntityValidator()<br />    {<br />        var types = Assembly.GetExecutingAssembly().GetTypes();<br /><br />        var validators =<br />            from type in types<br />            where !type.IsAbstract<br />            where typeof(IEntityValidator).IsAssignableFrom(type)<br />            select (IEntityValidator)Activator.CreateInstance(type);<br /><br />        Validators = validators.ToArray();<br />    }<br /><br />    public static void Validate(object context,<br />        IEnumerable&lt;object&gt; entities)<br />    {<br />        using (new ContextScope(context))<br />        {<br />            var invalidResults = (<br />                from validator in Validators<br />                from result in validator.Validate(entities)<br />                select result).ToArray();<br /><br />            // Throw an exception when there are invalid results.<br />            if (invalidResults.Length &gt; 0)<br />            {<br />                throw new ValidationException(invalidResults);<br />            }<br />        }<br />    }<br />}</pre><p>This new <span class="type">EntityValidator</span> implementation uses a plug-in model, where different validation modules can be added without any changes to existing code (The <a rel="external" href="http://en.wikipedia.org/wiki/Open/closed_principle" title="Wikipedia - Open/closed principle">Open/Closed principle</a>). The plug-ins must implement the <span class="type">IEntityValidator</span> interface. The static constructor of the <span class="type">EntityValidator</span> loads all available plug-ins by searching for all types in the same assembly that implement the <span class="type">IEntityValidator</span> interface. All found types will be instantiated and added to a static list.</p><p>Note that there are of course other possible implementations. For instance, a <a rel="external" href="http://en.wikipedia.org/wiki/Dependency_injection" title="Wikipedia - Dependency injection">dependency injection</a> framework (such as my own <a rel="external" href="http://simpleinjector.codeplex.com" title="Simple Injector - an easy-to-use Dependency Injection library">Simple Injector</a>) could be used to retrieve the list of <span class="type">IEntityValidator</span> implementations or you could create a plug-in model where the application loads assemblies located in a plugin directory (but I wouldn't advice this last option in this scenario). I chose this particular implementation, because it&rsquo;s both flexible and just a few lines of code (less code is important, because this plug-in model isn&rsquo;t the subject of this post).</p><p>The <span class="type">EntityValidator</span><span class="code">.Validate</span> method uses the static list of <span class="code">Validators</span> and invokes each validator's <span class="code">Validate</span> method. The validate method returns a collection of VAB <span class="type">ValidationResult</span> objects, one for each failed validation rule. The <span class="code">Validate</span> method has become even simpler than it was before. All framework dependent validations are now extracted from this method, which is good. What is left is the infrastructure.</p><p>Note that there is a little tweak from the previous implementation: The previous implementations used a collection of <span class="type">ValidationResults</span> objects (a <span class="type">ValidationResults</span> object is a staticly typed collection of <span class="type">ValidationResult</span> objects). In this new implementation we directly use a collection of <span class="type">ValidationResult</span> objects. The extra grouping made things more difficult than strictly needed.</p><p>What we need to do next is to create some implementations of the <span class="type">IEntityValidator</span> interface. Let's start with the VAB validation infrastructure:</p><pre class="cs" language="csharp" customtypes="ColumnAttribute ContextScope EntityValidator IEntityValidator LinqToSqlMaximumFieldLengthValidator LinqToSqlNullPropertyValidator VABEntityValidator  ValidationException ValidationFactory ValidationResult " customvaluetypes="PutYourCustomValueTypesHere">using System;<br />using System.Collections.Generic;<br />using System.Linq;<br />using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;<br />using Microsoft.Practices.EnterpriseLibrary.Validation;<br /><br />sealed class VABEntityValidator : IEntityValidator<br />{<br />    public IEnumerable&lt;ValidationResult&gt; Validate(<br />        IEnumerable&lt;object&gt; entities)<br />    {<br />        return<br />            from entity in entities<br />            let type = entity.GetType()<br />            let validator =<br />                ValidationFactory.CreateValidator(type)<br />            let results = validator.Validate(entity)<br />            where !results.IsValid<br />            from result in results<br />            select result;<br />    }<br />}</pre><p>This code should look pretty familiar. It's the code that was part of the <span class="type">EntityValidator</span><span class="code">.Validate</span> method in <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=46" title=".NET Junkie - Integrating Enterprise Library Validation Application Block With LINQ to SQL and Entity Framework Part 1: Basic Integration">part 1</a>. With this code our solution is back to it&rsquo;s old behavior.</p><p>Let's now define an entity validator that uses the LINQ to SQL metadata to validate properties that must not contain a null value:</p><pre class="cs" language="csharp" customtypes="PropertyInfo ColumnAttribute ContextScope EntityValidator IEntityValidator LinqToSqlMaximumFieldLengthValidator LinqToSqlNullPropertyValidator VABEntityValidator  ValidationException ValidationFactory ValidationResult " customvaluetypes="PutYourCustomValueTypesHere">using System.Collections.Generic;<br />using System.Data.Linq.Mapping;<br />using System.Linq;<br />using System.Reflection;<br /><br />class LinqToSqlNullPropertyValidator : IEntityValidator<br />{<br />    public IEnumerable&lt;ValidationResult&gt; Validate(<br />        IEnumerable&lt;object&gt; entities)<br />    {<br />        return<br />            from entity in entities<br />            from result in GetValidationResultsFor(entity)<br />            select result;<br />    }<br /><br />    private static IEnumerable&lt;ValidationResult&gt;<br />        GetValidationResultsFor(object entity)<br />    {<br />        var properties = entity.GetType().GetProperties();<br /><br />        return<br />            from property in properties<br />            where property.GetValue(entity, null) == null<br />            where !PropertyCanBeNull(property)<br />            select new ValidationResult(&quot;The value cannot be null.&quot;,<br />                entity, property.Name, null, null);<br />    }<br /><br />    private static bool PropertyCanBeNull(PropertyInfo property)<br />    {<br />        object[] columnAttributes = property.GetCustomAttributes(<br />            typeof(ColumnAttribute), true);<br /><br />        if (columnAttributes.Length == 0)<br />        {<br />            return true;<br />        }<br />         <br />        var column = (ColumnAttribute)columnAttributes[0];<br />        return column.IsDbGenerated || column.CanBeNull;<br />    }<br />}</pre><p><font color="#ff0000">&lt;Update 2010-03-07&gt;</font><br />There was a problem concerning database generated columns. I fixed a bug in the <span class="type">LinqToSqlNullPropertyValidator</span> by checking the <span class="code">IsDbGenerated</span> property.<br /><font color="#ff0000">&lt;/Update&gt;</font> </p><p>This relatively simple class uses LINQ extensively. Did I tell you how much I love LINQ for its expressiveness? :-). The class iterates all supplied entities and for each entity iterates its public properties to check whether it has been marked with a <a rel="external" href="http://msdn.microsoft.com/en-us/library/system.data.linq.mapping.columnattribute.aspx" title="MSDN - System.Data.Linq.Mapping.ColumnAttribute Class">ColumnAttribute</a>. If the attribute is found and it&rsquo;s <a rel="external" href="http://msdn.microsoft.com/en-us/library/system.data.linq.mapping.columnattribute.canbenull.aspx" title="MSDN - ColumnAttribute.CanBeNull Property ">CanBeNull</a> property is false while the actual property value is null, a <span class="type">ValidationResult</span> will be added to the returned collection.</p><p>While validating for null values is useful, checking the string length of a property would be even more useful. Here&rsquo;s the code to do this:</p><pre class="cs" language="csharp" customtypes="PropertyInfo ColumnAttribute ContextScope EntityValidator IEntityValidator LinqToSqlMaximumFieldLengthValidator LinqToSqlNullPropertyValidator VABEntityValidator  ValidationException ValidationFactory ValidationResult " customvaluetypes="PutYourCustomValueTypesHere">using System;<br />using System.Collections.Generic;<br />using System.Data.Linq.Mapping;<br />using System.Linq;<br />using System.Reflection;<br /><br />class LinqToSqlMaximumFieldLengthValidator : IEntityValidator<br />{<br />    public IEnumerable&lt;ValidationResult&gt; Validate(<br />        IEnumerable&lt;object&gt; entities)<br />    {<br />        return<br />            from entity in entities<br />            from result in GetMaxLengthErrorsFor(entity)<br />            select result;<br />    }<br /><br />    private static IEnumerable&lt;ValidationResult&gt;<br />        GetMaxLengthErrorsFor(object entity)<br />    {<br />        var properties = entity.GetType().GetProperties();<br /><br />        return<br />            from property in properties<br />            where property.PropertyType == typeof(string)<br />            let value = (string)property.GetValue(entity, null)<br />            let length = value == null ? 0 : value.Length<br />            where length &gt; 0<br />            let maximumLength = GetMaximumLength(property)<br />            where length &gt; maximumLength<br />            select BuildResult(entity, property, maximumLength);<br />    }<br /><br />    private static ValidationResult BuildResult(object entity,<br />        PropertyInfo property, int maximumLength)<br />    {<br />        const string FormatMessage =<br />            &quot;The length of the value must be less &quot; +<br />            &quot;or equal to {0} characters.&quot;;<br /><br />        string message =<br />            string.Format(FormatMessage, maximumLength);<br /><br />        return new ValidationResult(message, entity,<br />            property.Name, null, null);<br />    }<br /><br />    private static int GetMaximumLength(PropertyInfo property)<br />    {<br />        ColumnAttribute attribute =<br />            GetColumnAttribute(property);<br /><br />        if (attribute == null)<br />        {<br />            return Int32.MaxValue;<br />        }<br /><br />        string dbType = attribute.DbType;<br /><br />        if (!IsTruncatableTextType(dbType))<br />        {<br />            return Int32.MaxValue;<br />        }<br /><br />        int leftBracketIndex = dbType.IndexOf(&quot;(&quot;);<br />        int rightBracketIndex = dbType.IndexOf(&quot;)&quot;);<br /><br />        try<br />        {<br />            string length = dbType.Substring(leftBracketIndex + 1,<br />                rightBracketIndex - leftBracketIndex - 1);<br /><br />            return int.Parse(length);<br />        }<br />        catch (SystemException ex)<br />        {<br />            string message = string.Format(<br />                &quot;Property {0} of type {1} has a {2} defined &quot; +<br />                &quot;with a DbType with value '{3}'. The maximum &quot; +<br />                &quot;length of that text field can not be extracted.&quot;,<br />                property.Name, property.DeclaringType,<br />                typeof(ColumnAttribute), dbType);<br /><br />            throw new InvalidOperationException(message, ex);<br />        }<br />    }<br /><br />    private static ColumnAttribute GetColumnAttribute(<br />        PropertyInfo property)<br />    {<br />        object[] columnAttributes =<br />            property.GetCustomAttributes(typeof(ColumnAttribute), true);<br /><br />        if (columnAttributes.Length == 0)<br />        {<br />            return null;<br />        }<br /><br />        return ((ColumnAttribute)columnAttributes[0]);<br />    }<br /><br />    private static bool IsTruncatableTextType(string dbType)<br />    {<br />        StringComparison ignoreCase =<br />            StringComparison.InvariantCultureIgnoreCase;<br /><br />        return<br />            dbType != null &amp;&amp; (<br />            dbType.StartsWith(&quot;Char&quot;, ignoreCase) ||<br />            dbType.StartsWith(&quot;NChar&quot;, ignoreCase) ||<br />            dbType.StartsWith(&quot;VarChar&quot;, ignoreCase) ||<br />            dbType.StartsWith(&quot;NVarChar&quot;, ignoreCase));<br />    }<br />}</pre><p>This class is slightly more complicated than the previous one, but the concept is the same. The class iterates all supplied entities and for each entity iterates the entity's public string properties to check whether its value's length is longer than the maximum that is specified in the <span class="type">ColumnAttribute</span>. The <a rel="external" href="http://msdn.microsoft.com/en-us/library/system.data.linq.mapping.columnattribute.dbtype.aspx" title="MSDN - ColumnAttribute.DbType Property">DbType</a> property of the <span class="type">ColumnAttribute</span> specifies the length of the string. Problem here is that the <span class="code">DbType</span> property is a string and the maximum string length is buried within that string, which might be defined as: <font color="#a31515">&quot;NVarChar(15) NOT NULL&quot;</font>. That's why some dirty string splitting is going on.</p><p>Note that this is a bit naive implementation and it might be slow. I could imagine the class to cache the needed metadata to improve performance, but I leave this as an exercise for the reader.</p><p><font color="#ff0000">&lt;UPDATE 2010-01-31&gt;</font><br />I did some testing to compare the difference between the naive implementation and one that caches the metadata and I did this by validating 10.000 Employee entities (since Employee is the biggest entity in the Northwind domain). I measured an overhead of 0.5 ms per validated Employee entity on my dev box. This isn't that much, but a cached approach might be useful in situations where you validate large sets of entities.<br /><font color="#ff0000">&lt;/UPDATE&gt;</font><br /> </p><h6>Conclusion</h6><p>As you can see, after doing a bit refactoring, adding support for automatic validation according to the generated metadata is a breeze.</p><p>Happy validating.</p>
		]]></content>
		<author>
			<name>Steven</name>
		</author>
	</entry>
	
	
	
	<entry>
		<title>Research on botnets</title>
		<link rel="alternate" type="text/html" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=63" />
		<updated>2009-09-24T10:31:00+02:00</updated>
		<published>2009-09-24T10:31:00+02:00</published>
		<id>tag:pivotpowered,2012:NETJunkie.63</id>
		<link rel="related" type="text/html" href=""  />
		<summary type="text">I just watched an amazing Google Talk video on YouTube that explains how botnets work.</summary>
        <content type="html" xml:lang="en" xml:base="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=63"><![CDATA[
                I just watched an amazing Google Talk video on YouTube that explains how botnets work.Watch it here: <a rel="external" href="http://www.youtube.com/watch?v=2GdqoQJa6r4" title="YouTube - How to Steal a Botnet and What Can Happen When You Do">How to Steal a Botnet and What Can Happen When You Do</a>.
		]]></content>
		<author>
			<name>Steven</name>
		</author>
	</entry>
	
	
	
	<entry>
		<title>Preventing Cross-site Request Forgery (CSRF) Attacks Using ViewState</title>
		<link rel="alternate" type="text/html" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=62" />
		<updated>2010-11-18T14:23:00+02:00</updated>
		<published>2009-09-19T17:14:00+02:00</published>
		<id>tag:pivotpowered,2012:NETJunkie.62</id>
		<link rel="related" type="text/html" href=""  />
		<summary type="text">This article describes what Cross-site request forgery attacks are and how to mitigate them.</summary>
        <content type="html" xml:lang="en" xml:base="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=62"><![CDATA[
                This article describes what Cross-site request forgery attacks are and how to mitigate them.<p>Cross-site request forgery (CSRF) is &quot;<em>a type of malicious exploit of a website whereby unauthorized commands are transmitted from a user that the website trusts <a rel="external" href="http://en.wikipedia.org/wiki/Cross-site_request_forgery" title="Wikipedia - Cross-site request forgery">-&gt;</a></em>&quot;. A CSRF attack typically forces users to execute unwanted actions while they are logged into a trusted website. What basically happens with CSRF is that a bad guy lures your website's users to a webpage he controls. By crafting that page in specific way the attacker tricks the user's browser into sending requests to your website. When that user is logged in to your website at that time (or your site has a remember me option), the request is executed in the context of that user.</p><p>Wikipedia has <a rel="external" href="http://en.wikipedia.org/wiki/Cross-site_request_forgery" title="Wikipedia - Cross-site request forgery">a good example</a> of a CSRF attack where the attacker uses an HTML image tag to transmit a command in the context of the logged in user:</p><pre class="html" language="html">&lt;img src=&quot;http://bank.example/withdraw?account=bob&amp;amount=1000000&amp;for=mallory&quot;&gt;</pre><p>For this attack to be successful, the bank.example website must allow execution of commands through HTTP GET operations. One of the easiest ways in preventing CSRF attacks is preventing any mutations through GET operations. Only post backs should be able to trigger any transaction or change any state. This eliminates this particular type of CSRF attacks.</p><p>Disallowing GET for mutations however, is not enough. There is a second type of CSRF and it uses post backs. By creating a malicious (possibly hidden) form in a web page, the bad guy would trick the victim or the victim's browser into posting the form to your website. While it's easy to understand that PHP websites are vulnerable to this type of attack, sometimes .NET developers have the misconception that ASP.NET is safe, because the ViewState protects them. Well, the ViewState can protect you, but it doesn&rsquo;t do so by default.</p><p>As you know, the ASP.NET <a rel="external" href="http://weblogs.asp.net/infinitiesloop/archive/2006/08/03/truly-understanding-viewstate.aspx" title="Infinities Loop - TRULY Understanding ViewState">ViewState</a> is this block of <a rel="external" href="http://nl.wikipedia.org/wiki/Base64" title="Wikipedia - Base64">Base64</a> encoded data, containing the state of a web page, sent to the browser for storage between two requests. This data will be sent back to the web server on each post back. With a normal configuration, the ViewState data is not encrypted and can be <a rel="external" href="http://www.google.nl/search?q=viewstate+decoder" title="Google search: viewstate + decoder">read</a> by anyone who wishes to. However, because the ViewState contains a hash value (when <a rel="external" href="http://msdn.microsoft.com/en-us/library/system.web.ui.page.enableviewstatemac.aspx" title="MSDN - Page.EnableViewStateMac Property">EnableViewStateMac</a> is set to true, which is the default), it's practically impossible for it to be tampered with. A post back will only succeed if the ViewState is of an exact form. The nature of CSRF attacks doesn't enable the attacker to steal the user's ViewState from a page. But what developers often don't realize is that the ViewState isn't user specific (by default). Therefore, an attacker with access to the website (for instance when he has a user account) can simply copy the page's ViewState and use it to build the HTML form of his malicious web page.</p><p>When that form is posted to the website from the victim's browser, the ASP.NET website will, as always, validate that ViewState. However, because that ViewState isn't tampered with, the ViewState's hash is still valid for that particular page and the page is executed. When the user is logged in at that time, the CSRF attack is successful.</p><h5>Mitigating the risk</h5><p>There are several ways to mitigate the risk. The easiest way is by using the Page's <a rel="external" href="http://msdn.microsoft.com/en-us/library/system.web.ui.page.viewstateuserkey.aspx" title="MSDN - System.Web.UI.Page.ViewStateUserKey Property">ViewStateUserKey</a> property. You can set this property in the page's Init event. What will happen is that ASP.NET will use this value to generate the ViewState <a rel="external" href="http://en.wikipedia.org/wiki/Message_authentication_code" title="Wikipedia - Message authentication code">MAC</a> (which is the hash for the ViewState). This means that when the user key changed on a post back, the validation for the MAC will fail and a <span class="type">HttpException</span> will be thrown. The following example shows how to implement this protection in a web page:</p><pre class="cs" language="csharp" customtypes="InvalidOperationException">protected void Page_Init(object sender, EventArgs e)<br />{<br />    // Validate whether ViewState contains the MAC fingerprint<br />    // Without a fingerprint, it's impossible to prevent CSRF.<br />    if (!this.Page.EnableViewStateMac)<br />    {<br />        throw new InvalidOperationException(<br />            &quot;The page does NOT have the MAC enabled and the view&quot; +<br />            &quot;state is therefore vulnerable to tampering.&quot;);<br />    }<br /><br />    this.ViewStateUserKey = this.Session.SessionID;<br />}</pre><p>There are a few short comes to this solutions however. First of all, while using a SessionID is very safe, this means post backs wouldn't survive a AppDomain recycle. So it might be better to use the user name as user key. This however makes the ViewState valid for an infinite amount of time, which might be a risk that's to great. And while this mechanism works with pages that are protected by a login, it has some issues with public pages.<br /><br />Public pages can be accessed by people without a user name (or who's user name isn't known yet). The anonymous user name (presumably an empty string) will be used as <span class="code">ViewStateUserKey</span> and will therefore be used by ASP.NET to generate the MAC. However, when a user posts back that page after she logged in (for instance when the user opened multiple tabs in her browser) the user name changed and the MAC validation fails.<br /><br />When you expect your users to work with multiple tabs, and have a site that uses both public as private pages, it prevents you from using the presented code in a base page from which all pages in your application inherit. The mechanism might be fine though when defining a 'SecureBasePage' that implements this mechanism. All pages that must be protected by login can inherit from this page.<br /><br />This mechanism doesn't help you in protecting public pages. However, we should question the use of that. Public pages are accessible by everybody and they therefore shouldn't be able to change your application's state in the first place (except perhaps for things like a poll). Trying to protect something that's insecure by definition might be strange. Of course you have to think about what pages and data you give public exposure, but that is something you will hopefully find in the functional specs and it's not specific to CSRF. Also be careful by using public pages that add functionality once a user is logged in. It's hard to protect those type of pages against CSRF.</p><h5>A different approach <br /></h5><p>A few months ago, when helping a client of mine with some security issues in one of their web applications, I implemented a different approach. The CSRF prevention mechanism had to be implemented in the base page, but the system was based on a internal framework that used one single aspx page for all its functionality (both public and login protected) in the application (mostly based on dynamic loading of user controls). This basically rendered the use of the <span class="code">ViewStateUserKey</span> useless. What I came up with was an alternative mechanism, that stored the user name and a DateTime in the ViewState (in the control state to be more precise). This allowed the ViewState to be user specific and have a expiration time that was beyond a possible AppDomain recycle. Next, because the user name wasn't used to generate the ViewState MAC, I was able to do an alternative check and throw a more specific exception message on failure. I also allowed the validation to succeed when the user name, stored in the ViewState, or the currently logged in user name where unknown. This allowed the system to work properly when users posted back public pages with a login or logout in between. The solution looked much like this:</p><pre class="cs" language="csharp" customtypes="CsrfBasePage Page Pair InvalidOperationException SecurityException HttpContext">using System;<br />using System.Security;<br />using System.Web.UI;<br /><br />public abstract class CsrfBasePage : System.Web.UI.Page<br />{<br />    // Expiration time of 12 hours.<br />    private static readonly TimeSpan ExpirationTime =<br />        new TimeSpan(0, 12, 0, 0);<br /><br />    private string controlStateUserName;<br />    private DateTime controlStateGenerationDate;<br /><br />    protected override void OnInit(EventArgs e)<br />    {<br />        this.RegisterRequiresControlState(this);<br />        base.OnInit(e);<br />    }<br /><br />    protected override void LoadControlState(object savedState)<br />    {<br />        Pair controlStatePair = (Pair)savedState;<br /><br />        Pair csrfData = (Pair)controlStatePair.First;<br /><br />        this.controlStateUserName = (string)csrfData.First;<br />        this.controlStateGenerationDate = (DateTime)csrfData.Second;<br /><br />        base.LoadControlState(controlStatePair.Second);<br />    }<br /><br />    protected override void OnLoad(EventArgs e)<br />    {<br />        this.PreventPostbackCSRF();<br /><br />        base.OnLoad(e);<br />    }<br /><br />    protected override object SaveControlState()<br />    {<br />        // The control state is used to store user name and date time.<br />        // Control state is part of the view state, but it's impossible<br />        // to disable it, so this solution will also work when the<br />        // viewstate is disabled.<br />        string currentUserName = UserRepository.GetCurrentUserName();<br />        DateTime controlStateGenerationTime = DateTime.Now;<br /><br />        Pair csrfData = <br />            new Pair(currentUserName, controlStateGenerationTime);<br /><br />        return new Pair(csrfData, base.SaveControlState());<br />    }<br /><br />    private void PreventPostbackCSRF()<br />    {<br />        // Validate whether ViewState contains the MAC fingerprint<br />        // Without a fingerprint, it's impossible to prevent CSRF.<br />        if (!this.Page.EnableViewStateMac)<br />        {<br />            throw new InvalidOperationException(<br />                &quot;The page does NOT have the MAC enabled and the view&quot; +<br />                &quot;state is therefore vurnerable to viewstate tampering.&quot;);<br />        }<br /><br />        if (this.IsPostBack)<br />        {<br />            string currentlyLoggedInUserName = <br />                HttpContext.Current.User.Identity.Name;<br /><br />            ValidateUserName(currentlyLoggedInUserName);<br /><br />            ValidateGenerationDate();<br />        }<br />    }<br /><br />    private void ValidateUserName(string loggedInUser)<br />    {<br />        bool userIsValid = this.controlStateUserName == loggedInUser;<br />        bool pageIsPublic = this.IsCurrentPagePublic(loggedInUser);<br /><br />        if (!userIsValid &amp;&amp; !pageIsPublic)<br />        {<br />            string message = string.Format(<br />                &quot;A possible Cross-site Request Forgery attack &quot; +<br />                &quot;is detected. ViewState was generated by user &quot; +<br />                &quot;'{0}', but the current user is '{1}'.&quot;,<br />                controlStateUserName, loggedInUser);<br /><br />            throw new SecurityException(message);<br />        }<br />    }<br /><br />    private bool IsCurrentPagePublic(string loggedInUser)<br />    {<br />        // Because it's impossible to tamper with the view state, when<br />        // either the control state user name or the actual username<br />        // are null or empty, the current page must be a public page.<br />        return String.IsNullOrEmpty(this.controlStateUserName) ||<br />            String.IsNullOrEmpty(loggedInUser);<br />    }<br /><br />    private void ValidateGenerationDate()<br />    {<br />        if (this.IsViewStateTooOld)<br />        {<br />            throw new SecurityException(&quot;The ViewState is expired.&quot;);<br />        }<br />    }<br /><br />    private bool IsViewStateTooOld<br />    {<br />        get<br />        {<br />            DateTime expirationTime =<br />                this.controlStateGenerationDate + ExpirationTime;<br /><br />            return expirationTime &lt; DateTime.Now;<br />        }<br />    }<br />}</pre><p>While the implementation with the <span class="code">ViewStateUserKey</span> is much easier, the code above fixes the short comes of the <span class="code">ViewStateUserKey</span> and will hopefully serve some of you.</p><p><font color="#ff0000">UPDATE 2010-11-18: Please use this post for its education value. Instead of using the article's code however, please visit the <a rel="external" href="http://anticsrf.codeplex.com/" title="AntiCSRF">AntiCSRF project</a> on CodePlex. It use a much cleaner approach that doesn't depend on inheriting from a base class. </font></p>
		]]></content>
		<author>
			<name>Steven</name>
		</author>
	</entry>
	
	
	
	<entry>
		<title>Microsoft Anti-Cross Site Scripting Library 3.1 released</title>
		<link rel="alternate" type="text/html" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=61" />
		<updated>2009-09-19T12:44:00+02:00</updated>
		<published>2009-09-19T12:44:00+02:00</published>
		<id>tag:pivotpowered,2012:NETJunkie.61</id>
		<link rel="related" type="text/html" href=""  />
		<summary type="text">The Microsoft Anti-Cross Site Scripting Library (Anti-XSS) is an encoding library designed to help developers protect their ASP.NET web-based applications from XSS attacks.</summary>
        <content type="html" xml:lang="en" xml:base="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=61"><![CDATA[
                The Microsoft Anti-Cross Site Scripting Library (Anti-XSS) is an encoding library designed to help developers protect their ASP.NET web-based applications from XSS attacks.<p>New features in version 3.1 of the Microsoft Anti-Cross Site Scripting Library include:</p><ul><li>An expanded white list that supports more languages.</li><li>Performance improvements.</li><li>Support for Shift_JIS encoding for mobile browsers.</li><li>Security Runtime Engine (SRE) HTTP module.</li><li>HTML Sanitization methods to strip dangerous HTML scripts.</li></ul>You can download AntiXSS 3.1 <a rel="external" href="http://www.microsoft.com/downloads/details.aspx?familyid=051EE83C-5CCF-48ED-8463-02F56A6BFC09&amp;displaylang=en" title="Microsoft Download Center - Microsoft Anti-Cross Site Scripting Library V3.1">here</a>.
		]]></content>
		<author>
			<name>Steven</name>
		</author>
	</entry>
	
	
	
	<entry>
		<title>NDepend</title>
		<link rel="alternate" type="text/html" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=60" />
		<updated>2011-04-01T13:42:00+02:00</updated>
		<published>2009-09-14T17:50:00+02:00</published>
		<id>tag:pivotpowered,2012:NETJunkie.60</id>
		<link rel="related" type="text/html" href=""  />
		<summary type="text">For over three years I've been using NDepend. In this post I'll describe my thoughts on NDepend.</summary>
        <content type="html" xml:lang="en" xml:base="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=60"><![CDATA[
                For over three years I've been using NDepend. In this post I'll describe my thoughts on NDepend.<p><img src="http://www.cuttingedge.it/blogs/steven/images/ndependart.jpg" style="float:right;margin-left:10px;margin-bottom:5px;border:1px solid" title="" alt="" class="pivot-image" />As a freelancer I participate in several projects each year. Their size, quality, and size differ quite a lot, but a few times a year I feel the urge of using <a rel="external" href="http://ndepend.com/" title="NDepend">NDepend</a> on those projects. It helps me understand code bases from an architectural point of view. While it is useful for a lot of stuff, I mainly use it to analyze and visualize the dependencies between assemblies, namespaces, classes, and get an overall picture of how a project is designed or to figure out what the desired design should be. More than once, code has been written without any architectural vision, and when there was such a vision, there hardly ever is any documentation of it and the developers don't stick to this vision.<br /><br />One area where NDepend can really shine is validating a code base on a prescribed architecture. While I must admit I've never been in the opportunity to integrate NDepend in a build process, NDepend is the tool that you run next to <a rel="external" href="http://en.wikipedia.org/wiki/FxCop" title="Wikipedia - FxCop">FxCop</a> (code analysis), <a rel="external" href="http://code.msdn.microsoft.com/sourceanalysis" title="StyleCop">StyleCop</a> (source analysis), and <a rel="external" href="http://www.ncover.com/" title="NCover">NCover</a> on your build server. In the past I've written automated architectural tests that for instance validate that <span class="type">LinqDataSource</span> and <span class="type">SqlDataSource</span> controls aren't used in a ASP.NET web application. Those tests used reflection to analyze all private fields of classes inheriting from <span class="code">System.Web.</span><span class="type">Page</span>. While writing such tests was doable, NDepend not only makes this a lot easier, there are a lot of architectural rules that are simply impossible to test using reflection. You might for instance forbid the use of <span class="type">DateTime</span><span class="code">.Now</span> (and the like) in your business layer (because you&rsquo;d rather want to use an interface that abstracts away getting the current time, such as log4net&rsquo;s <a rel="external" href="http://logging.apache.org/log4net/release/sdk/log4net.Appender.RollingFileAppender.IDateTime.html" title="log4net SDK Reference - RollingFileAppender.IDateTime Interface">IDateTime interface</a>). While you might achieve this by calling the introspection engines <a rel="external" href="http://www.mono-project.com/Cecil" title="Mono.Cecil">Mono.Cecil</a> or Microsoft's <a rel="external" href="http://ccimetadata.codeplex.com/" title="Common Compiler Infrastructure: Metadata components">CCI</a> in your automated architectural tests, this is quite hellish. You'd be better of using NDepend. Using the NDepend <a rel="external" href="http://ndepend.com/Features.aspx#CQL" title="NDepend - Code Query Language (CQL)">Code Query Language</a> [CQL] such a test would look like this:</p><p><font color="#0000ff">    WARN IF </font>Count &gt; 0<font color="#0000ff"> IN SELECT METHODS</font> <br /><font color="#0000ff">    WHERE </font>IsDirectlyUsing <font color="#800000">&quot;System.DateTime.get_Now()&quot;</font><br /><font color="#0000ff">    OR </font>IsDirectlyUsing <font color="#800000">&quot;System.DateTime.get_Today()&quot; </font><br /><font color="#0000ff">    OR </font>IsDirectlyUsing <font color="#800000">&quot;System.DateTime.get_UtcNow()&quot;</font> </p>The last few years I've been using the free <a rel="external" href="http://ndepend.com/NDependDownload.aspx" title="NDepend - Trial / Open Source / Academic Edition download">Trial / Academic Edition</a> for all those projects, which has it short comes. For that reason I was very pleased to get an mail from <a rel="external" href="http://codebetter.com/blogs/patricksmacchia" title="Patrick Smacchia's weblog">Patrick Smacchia</a>, the creator of NDepend, who offered me a free personal edition that I can use at home and on-site when I'm working for a client. While he demanded nothing in return, he of course hopes me to blog about this, which -as you can see- I'm doing right now. While of course this 'gift' encouraged me to blog about this, I can honestly say this is one of those tools that saves my day.<br /><br />Of course there are some things I dislike about NDepend. The biggest annoyance I have with it is this Code Query Language. While the language looks like SQL and the designer uses some sort of IntelliSense, I never really can get the hang of it. I rather see NDepend inject all project metadata into a SQL server database so I can really query it using SQL. I discussed this lately with Patrick and he convinced me this isn't feasible. The problem is however, that the only query languages I know well are Microsoft T-SQL and C# LINQ. CQL is (of course) different (because it's a domain specific language), and while it might not be difficult to work with, I just use NDepend and especially CQL too little to get the hang of it. I wish CQL would work more like LINQ with a clear object model and rich IntelliSense support (vote for more linqishness <a rel="external" href="http://spreadsheets.google.com/viewform?hl=en&amp;formkey=dGlWaUdLVFR3YW9NTDQ5emRRVVZWc2c6MA.." title="Online questionnaire - Influence the future of NDepend">here</a>). Fortunately, NDepend uses context sensitive menu's that allow you to create common CQL queries. This makes things much more easier.<br /><br />Another thing that sometimes annoys me is the NDepend UI. The application consists of several parts that can be moved around on the screen or can be docked, much like you can do with Visual Studio. But the docking just doesn't work that great and I sometimes manage to move the parts in such a way that the UI becomes unworkable. I think it is for this reason NDepend contains a 'Reset views' option (CTRL + SHIFT + R). This misbehavior might be caused by the <a rel="external" href="http://www.devexpress.com/products/VCL/Exbars/DockingLib.xml" title="Devexpress - ExpressDocking Library ">Devexpress docking library</a> that NDepend uses internally, nevertheless I find it a bit annoying. However, I must say after discussing this with Patrick, I wasn't able to reproduce this. But again: 'Reset views' is your friend ;-).<br /><br />But even with these short comes, for me NDepend is a great tool. I have no doubt that these short comes will be solved in future releases. However, NDepend is not a tool for every developer's toolbox. The tool is especially suited for architects and lead developers that understand the importance of architecture and are working one medium to large code bases. If that's you, and haven't tried NDepend, you should.
		]]></content>
		<author>
			<name>Steven</name>
		</author>
	</entry>
	
	
	
	<entry>
		<title>CuttingEdge.Conditions version 1.0 released</title>
		<link rel="alternate" type="text/html" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=59" />
		<updated>2011-04-01T13:43:00+02:00</updated>
		<published>2009-09-07T16:51:00+02:00</published>
		<id>tag:pivotpowered,2012:NETJunkie.59</id>
		<link rel="related" type="text/html" href=""  />
		<summary type="text">Last week I published the first stable release of CuttingEdge.Conditions.</summary>
        <content type="html" xml:lang="en" xml:base="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=59"><![CDATA[
                Last week I published the first stable release of CuttingEdge.Conditions.<p><strong>Download:</strong><br /><em>The CuttingEdge.Conditions library and source code can be downloaded from CodePlex.com. Visit the homepage at <a rel="external" href="http://conditions.codeplex.com" title="CuttingEdge.Conditions home page">conditions.codeplex.com</a> or go directly to the <a rel="external" href="http://conditions.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=31750" title="CuttingEdge.Conditions v1.0 download page">download tab</a>.</em><br /><br /><img src="http://www.cuttingedge.it/blogs/steven/images/conditions.jpg" style="float:right;margin-left:10px;margin-bottom:5px;border:1px solid" title="" alt="" class="pivot-image" />As you might know, CuttingEdge.Conditions is a library that helps developers to write pre- and postcondition validations in their C# 3.0 and VB9 code base. It's over a year ago that <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=36" title=".NET Junkie - My Own Fluent Argument Validation Library">I first blogged</a> about Conditions (before it actually got a name) and two posts followed with the <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=38" title=".NET Junkie - Introducing CuttingEdge.Conditions">official introduction</a>  of the library and a some information about <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=39" title=".NET Junkie - Extending CuttingEdge.Conditions">how to extend it</a>.<br /><br />This first stable release has had a major face lift and several minor bug fixes. The API has changed considerably and therefore this release is both binary and code incompatible with the previous beta. Great change is the possibility to run CuttingEdge.Conditions on machines that do not have .NET 3.5 installed. While the assembly itself is still dependent on System.Core (.NET 3.5), users can safely add it to their .NET 2.0 projects (as long as the C# 3.0 or VB9 compilers are used).<br /><br />Conditions is now released under a different license. The source code is now released under the MIT License. The source code was previously released under the more restrictive LGPL license.<br /><br />The two other most important changes are the <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=57" title=".NET Junkie - Controversial change in CuttingEdge.Conditions">removal of the extension method behavior of the Requires() and Ensures() entry point methods</a>, and the <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=58" title=".NET Junkie - Removing Otherwise method from CuttingEdge.Conditions">removal of the Otherwise methods</a>. I blogged about these changes two weeks ago.</p><p>For the complete list of changes, please visit the <a rel="external" href="http://conditions.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=31750" title="CuttingEdge.Conditions v1.0 download page">release tab</a> on CodePlex.</p><p>A lot of work has gone into the building of CuttingEdge.Conditions. The project currently consists of <strong>5163</strong> lines of code, 1653 lines in the library and 3510 lines in the unit test project, (thanks to <a rel="external" href="http://www.ndepend.com" title="NDepend">NDepend</a> for counting) and a massive amount of <strong>1275</strong> unit tests with a test coverage of <strong>100%</strong> (thanks to <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=51" title=".NET Junkie - NCover supports CuttingEdge.Conditions">NCover</a> for the support). The library consists of <strong>376</strong> extenstion methods for <strong>43</strong> different checks.</p><p>Happy validating!</p>
		]]></content>
		<author>
			<name>Steven</name>
		</author>
	</entry>
	
	
	
	<entry>
		<title>Removing Otherwise method from CuttingEdge.Conditions</title>
		<link rel="alternate" type="text/html" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=58" />
		<updated>2010-02-14T22:48:00+02:00</updated>
		<published>2009-08-26T13:36:00+02:00</published>
		<id>tag:pivotpowered,2012:NETJunkie.58</id>
		<link rel="related" type="text/html" href=""  />
		<summary type="text">In this post Ill describe another breaking change Im making to my open source project, CuttingEdge.Conditions.</summary>
        <content type="html" xml:lang="en" xml:base="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=58"><![CDATA[
                In this post I&rsquo;ll describe another breaking change I&rsquo;m making to my open source project, CuttingEdge.Conditions.<p>You might noticed I'm <a rel="external" href="http://conditions.codeplex.com/SourceControl/ListDownloadableCommits.aspx" title="CuttingEdge.Conditions - Recent Check-ins">working</a> on <a rel="external" href="http://conditions.codeplex.com/" title="CuttingEdge.Conditions @ CodePlex">CuttingEdge.Conditions</a> again; my open source library on <a rel="external" href="http://www.codeplex.com/" title="CodePlex">Microsoft's CodePlex</a>. Two days ago I described a <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=57" title=".NET Junkie - Controversial change in CuttingEdge.Conditions">controversial breaking change in CuttingEdge.Conditions</a>.</p><p>Today I want to write about another breaking change that I'll be making in the <a rel="external" href="http://conditions.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=31750" title="CuttingEdge.Conditions v1.0">coming stable release</a> of CuttingEdge.Conditions: I'm removing the <span class="code">Otherwise&lt;TException&gt;</span> methods from the library.</p><p>The <span class="code">Otherwise&lt;T&gt;</span> method overloads let users define the exception type that has to be thrown. Normally the library throws an <span class="type">ArgumentException</span> (using Requires) or <span class="type">PostconditionException</span> (using Ensures). Sometimes however, it's useful to throw another exception type and with the beta releases, CuttingEdge.Conditions lets you do this.</p><p>The name of the <span class="code">Otherwise</span> method is based on <a rel="external" href="http://research.microsoft.com/en-us/projects/specsharp/" title="Microsoft Research - Spec#">Spec#</a> (SpecSharp). I looked closely at the Spec# language, while designing CuttingEdge.Conditions. Besides <span class="keyword">requires</span> and <span class="keyword">ensures</span>, Spec# defines an <span class="keyword">otherwise</span> keyword. <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=36#The_API_must_use_the_same_terminology_as_SpecSharp_does" title=".NET Junkie - My Own Fluent Argument Validation Library - requirement: The API must use the same terminology as Spec# does">One of the requirements</a> I had in the <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=36" title=".NET Junkie - My Own Fluent Argument Validation Library">initial design</a> of Conditions was to use the same terminology as Spec#.</p><p>There are however, two problems with Otherwise:</p><h6>1. The name of the method doesn't properly describe its intend.</h6><p>While Otherwise follows Spec#, I noticed developers find the name confusing. While documentation helps, I think it&rsquo;s name can be improved. This means that I break with the initial requirement of staying close to Spec#, but I think this is okay. It could take years before Spec# (or its syntax) becomes mainstream I think it&rsquo;s better to make a library that&rsquo;s usable right now.</p><h6>2. The use isn't intuitive, which leads to programming mistakes.</h6><p>Perhaps it's the lack of proper documentation, lack of proper code samples, or simply a quirk in the design, but I recently experienced developers writing code like this:</p><pre class="cs badcode_top" language="csharp" customtypes="Condition InvalidOperationException" customvaluetypes="PutYourCustomValueTypesHere"><br />Condition.Requires(x)<br />    .IsNotNull()<br />    .Otherwise&lt;InvalidOperationException&gt;();<br /><br /></pre><p>The developers who wrote this code, expected an <span class="type">InvalidOperationException</span> to be thrown when x was null. This is not the case however. This code throws an <span class="type">ArgumentNullException</span>. The <span class="code">Requires()</span>, <span class="code">Ensures()</span>, and <span class="code">Otherwise()</span> methods return an object that will be passed to validation methods such as the <span class="code">IsNotNull()</span> method in the snippet above. That object determines the exception type to be thrown. When the <span class="code">Otherwise</span> is specified last, the object it returns will never get used. The right way to write this is:</p><pre class="cs" language="csharp" customtypes="Condition InvalidOperationException" customvaluetypes="PutYourCustomValueTypesHere">Condition.Requires(x)<br />    .Otherwise&lt;InvalidOperationException&gt;()<br />    .IsNotNull();<br /></pre><p>The problem however is that this is perhaps not as intuitive as I had expected.<br /><br />For these two reasons I'm not sure the current implementation is the right one. However, it's not clear to me what the correct design is. I'm finalizing the first stable release of the library at the moment. Leaving the current implementation in, means I can never change or remove it, without introducing a breaking change in a stable product. This would possibly lead to many angry users, which is something I like to prevent.<br /><br />While I know I might frustrate users of the current beta release, for most of them, <span class="code">Otherwise</span> is a rarely used feature. Therefore I think it's better to remove it before the stable release and let the user community participate in an improved design of the otherwise feature.<br /><br />The consequence of this change is that users will have to revert to using old fashion &lsquo;<span class="keyword">if</span><span class="code"> (...) </span><span class="keyword">throw</span><span class="code"> ex</span>&rsquo; statements in these situations. Although I published some code that could be added to your code base that fixed the breaking change I discussed <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=57" title=".NET Junkie - Controversial change in CuttingEdge.Conditions">two days ago</a>, this isn&rsquo;t possible in this case. It&rsquo;s not possible to supply code that will prevent you from making changes throughout your code base. <br /><br />But if you&rsquo;re so hooked on this way of validating that you don&rsquo;t want to go back to old fashion throw statements, please <a rel="external" href="http://conditions.codeplex.com/Thread/List.aspx" title="CuttingEdge.Conditions - Discussions on Code Plex">participate</a> and let us together get a better implementation. Also if you&rsquo;re really interested, I have an implementation with a slightly different syntax, that you actually can use in your own code base. If you&rsquo;re interested, let me know.</p><p>Cheers</p>
		]]></content>
		<author>
			<name>Steven</name>
		</author>
	</entry>
	
	
	
	<entry>
		<title>Controversial change in CuttingEdge.Conditions</title>
		<link rel="alternate" type="text/html" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=57" />
		<updated>2011-04-01T13:43:00+02:00</updated>
		<published>2009-08-24T17:49:00+02:00</published>
		<id>tag:pivotpowered,2012:NETJunkie.57</id>
		<link rel="related" type="text/html" href=""  />
		<summary type="text">In this post Ill describe a controversial change Im making in my open source project, CuttingEdge.Conditions.</summary>
        <content type="html" xml:lang="en" xml:base="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=57"><![CDATA[
                In this post I&rsquo;ll describe a controversial change I&rsquo;m making in my open source project, CuttingEdge.Conditions.<p><img src="http://www.cuttingedge.it/blogs/steven/images/conditions.jpg" style="float:right;margin-left:10px;margin-bottom:5px;border:1px solid" title="" alt="" class="pivot-image" />For a long time I had my doubts about a particular part of the API of my <a rel="external" href="http://conditions.codeplex.com/" title="CuttingEdge.Conditions @ CodePlex">CuttingEdge.Conditions</a> library and these doubts were the main reason that kept me from releasing a stable version of CuttingEdge.Conditions. I decided to try to get in contact with users of my library to find out what they thought of this particular issue I was having. This lead to the following controversial change:</p><p><font color="#ff0000">I&rsquo;m removing the extension method behavior of the Requires() and Ensures() entry point methods.</font><br /><br />This means that the following syntax is not supported anymore:</p><pre class="cs" language="csharp" customtypes="PutYourCustomTypesHere" customvaluetypes="PutYourCustomValueTypesHere">    x.Requires().IsNotNull();</pre><p>Instead the snippet above has to be written as follows:</p><pre class="cs" language="csharp" customtypes="Condition" customvaluetypes="PutYourCustomValueTypesHere">    Condition.Requires(x).IsNotNull();</pre><p>This decision is controversial, because the whole concept of the library was based on <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=36" title=".NET Junkie - My Own Fluent Argument Validation Library">this initial syntax</a> and I know many developers like this fluent way of writing validations. There are however several issues with this syntax, so please bear with me, as I&rsquo;ll try to explain why I decided to make this change.</p><p>The <a rel="external" href="http://conditions.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=31750" title="CuttingEdge.Conditions v1.0">coming stable release</a> of CuttingEdge.Conditions will contain this change.<br /><br /><font color="#ff0000">Please note that this post also supplies some code that you can add to your project that allows you to revert to the old syntax.</font></p><h5>Five reasons to change</h5><p>There are mainly five reasons why I decided to drop the extension behavior on the <span class="code">Requires()</span> and <span class="code">Ensures()</span> entry point methods. </p><h6>1. Not all .NET languages fully support the old syntax.</h6><p>The <span class="code">Requires()</span> and <span class="code">Ensures()</span> methods extended <span class="code">System.Object</span> and VB.NET can not handle extension methods on <span class="code">System.Object</span> due to its late binding capabilities. Calling <span class="code">obj.Requires()</span> would result in a runtime exception. For this reason the <a rel="external" href="http://conditions.codeplex.com/" title="CuttingEdge.Conditions @ CodePlex">Conditions homepage</a> on CodePlex already used the <span class="code">Condition.Requires</span> syntax in the VB examples. Because of this, the <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=31" title=".NET Junkie - Book: Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries">Framework Design Guidelines</a> warn against the use of extension methods on the type <span class="code">System.Object</span>.</p><h6>2. The extension methods clutter IntelliSense.</h6><p>The <span class="code">Requires()</span> and <span class="code">Ensures()</span> method are shown in the IntelliSense drop down list for each and every object in the IDE; even when a developer isn't validating. This clutters the IntelliSense and this could confuse developers.</p><h6>3. C# code snippets are less productive when generated with extension methods.</h6><p>While the code snippets engine of the VB.NET IDE allows the insertion of namespaces, the C# IDE does not have this ability (and we shouldn't expect <a rel="external" href="https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=353131" title="Microsoft Connect - Let a code snippet auto insert a namespace at the top of your page.">such a feature</a> to be added soon). Normally, this isn't a big problem, because the C# IDE makes it easy to include a missing namespace, by pressing CTRL + DOT, ENTER on a type. When using extension methods however, the C# IDE is unable to determine the namespace of the extension method (because there is no type specified explicitly). This means that a developer must still add the CuttingEdge.Conditions namespace manually on the top of the file, after using one of the code snippets. However, when the code snippets generate '<span class="code">Condition.Requires(x, &quot;x&quot;)</span>', a developer can move his cursor to the unknown <span class="type">Condition</span>  type and let the IDE insert the missing namespace very quickly.</p><h6>4. Recognizing blocks of pre- and postconditions is easier with the new syntax.</h6><p>This is actually a argument I heard from several developers, who use Conditions in their production code. Although <span class="code">x.Requires().IsNotNull()</span> syntax is very readable as an individual line, most methods will have several lines of preconditions, and those developers noted that the <span class="code">Condition.Requires(x)</span> syntax groups those statements very nicely together. I must say I agree with them.</p><h6>5. Leaving extension methods out of the library allows developers to choose one over the other.</h6><p>It's actually pretty easy (as I will show shortly) to add some code in your own project that defines <span class="code">Requires()</span> and <span class="code">Ensures()</span> extension methods. However, when Conditions defines those methods as extension methods, developers have no possibility to remove them (unless of course they create a private build of the library). An option would be to define the extension methods in another namespace within the Conditions assembly, as the Framework Design Guidelines advice, but I&rsquo;m not fond of that idea in this situation. This means that the developers using extension methods, have to include two namespaces in each file and this is less intuitive.<br /><br />I hope I've convinced you that this change is for the better, but if you, despite my arguments, still want the old syntax, please include the following code in your project. Most convenient is to put this class in the root namespace of your project.</p><pre class="cs" language="csharp" customtypes="ConditionValidator Condition" customvaluetypes="PutYourCustomValueTypesHere">using CuttingEdge.Conditions;<br /><br />/// &lt;summary&gt;<br />/// This class defines extension methods for the <br />/// CuttingEdge.Conditions Requires and Ensures entry point <br />/// methods.<br />/// &lt;/summary&gt;<br />internal static class ConditionExtensions<br />{<br />    /// &lt;summary&gt;<br />    /// Returns a new &lt;see cref=&quot;ConditionValidator{T}&quot; /&gt; that allows<br />    /// you to validate the preconditions of the given argument, given<br />    /// it a default ArgumentName of 'value'.<br />    /// &lt;/summary&gt;<br />    public static ConditionValidator&lt;T&gt; Requires&lt;T&gt;(this T value)<br />    {<br />        return Condition.Requires&lt;T&gt;(value);<br />    }<br /><br />    /// &lt;summary&gt;<br />    /// Returns a new &lt;see cref=&quot;ConditionValidator{T}&quot; /&gt; that allows<br />    /// you to validate the preconditions of the given argument.<br />    /// &lt;/summary&gt;<br />    public static ConditionValidator&lt;T&gt; Requires&lt;T&gt;(this T value,<br />        string argumentName)<br />    {<br />        return Condition.Requires&lt;T&gt;(value, argumentName);<br />    }<br /><br />    /// &lt;summary&gt;<br />    /// Returns a new &lt;see cref=&quot;ConditionValidator{T}&quot; /&gt; that allows<br />    /// you to validate the given argument, given it a default<br />    /// ArgumentName of 'value'.<br />    /// &lt;/summary&gt;<br />    public static ConditionValidator&lt;T&gt; Ensures&lt;T&gt;(this T value)<br />    {<br />        return Condition.Ensures&lt;T&gt;(value);<br />    }<br /><br />    /// &lt;summary&gt;<br />    /// Returns a new &lt;see cref=&quot;Validator{T}&quot;&gt;Validator&lt;/see&gt; that<br />    /// allows you to validate the postconditions of the given object.<br />    /// &lt;/summary&gt;<br />    public static ConditionValidator&lt;T&gt; Ensures&lt;T&gt;(this T value,<br />        string argumentName)<br />    {<br />        return Condition.Ensures&lt;T&gt;(value, argumentName);<br />    }<br />}<br /></pre><p>As always: Happy validating ;-)</p>
		]]></content>
		<author>
			<name>Steven</name>
		</author>
	</entry>
	
	
	
	<entry>
		<title>The evilness of ApplicationException</title>
		<link rel="alternate" type="text/html" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=56" />
		<updated>2009-08-20T19:47:00+02:00</updated>
		<published>2009-08-20T13:14:00+02:00</published>
		<id>tag:pivotpowered,2012:NETJunkie.56</id>
		<link rel="related" type="text/html" href=""  />
		<summary type="text">This post explains whats wrong with ApplicationException and why it should not be used.</summary>
        <content type="html" xml:lang="en" xml:base="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=56"><![CDATA[
                This post explains what&rsquo;s wrong with ApplicationException and why it should not be used.<p>For over three years the <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=31" title=".NET Junkie - Book: Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries">Framework Design Guidelines</a> (also available <a rel="external" href="http://msdn.microsoft.com/en-us/library/ms229042.aspx" title="Online version of the Framework Design Guidelines">online on MSDN</a>) make a clear statement about the use of <a rel="external" href="http://msdn.microsoft.com/en-us/library/system.applicationexception.aspx" title="MSDN - .NET Framework Class Library - ApplicationException Class">ApplicationException</a>:</p><blockquote>DO NOT throw or derive from System.ApplicationException.</blockquote><p>The reason for the existence of <span class="type">ApplicationException</span> is explained by <a rel="external" href="http://www.wintellect.com/cs/blogs/jeffreyr/default.aspx" title="Jeffrey Richter's Blog">Jeffrey Richter</a> in the Framework Design Guidelines:</p><blockquote>The original idea was that classes derived from SystemException would indicate exceptions thrown from the CLR (or system) itself, whereas non-CLR exceptions would be derived from ApplicationException.</blockquote><p>There are two problems with this idea however. First of all it's very questionable if there is any use in separating CLR exceptions from non-CLR exceptions. You hardly ever want to catch all non-CLR exceptions or inverse: catch CLR exceptions. They are both just too general to catch. Second, not all exceptions in the .NET framework follow this pattern; some CLR exceptions do inherit from <span class="type">ApplicationException</span> (such as <a rel="external" href="http://msdn.microsoft.com/en-us/library/system.reflection.targetexception.aspx" title="MSDN - .NET Framework Class Library - TargetException Class">TargetException</a>, <a rel="external" href="http://msdn.microsoft.com/en-us/library/system.reflection.targetinvocationexception.aspx" title="MSDN - .NET Framework Class Library - TargetInvocationException Class">TargetInvocationException</a> and <a rel="external" href="http://msdn.microsoft.com/en-us/library/system.threading.waithandlecannotbeopenedexception.aspx" title="MSDN - .NET Framework Class Library - WaitHandleCannotBeOpenedException Class">WaitHandleCannotBeOpenendException</a>). This defeats the whole idea of having an <span class="type">ApplicationException</span> in the first place. <br /><br />While Framework Design Guidelines are very clear about this, outdated documents and guidelines are still floating on the web that recommend using <span class="type">ApplicationException</span>. Some even published by Microsoft!<br />    <br />The <span class="type">ApplicationException</span> in itself isn't considered harmful, inheriting from it is just considered <a rel="external" href="http://blogs.msdn.com/kcwalina/archive/2006/06/23/644822.aspx" title="Krzysztof Cwalina - ApplicationException considered useless">useless</a>. It gets harmful, when catching <span class="type">ApplicationException</span>. Not only does the .NET framework itself throw exceptions that derive from <span class="type">ApplicationException</span>, but a lot popular frameworks you might use in your production code throw exceptions that derive from <span class="type">ApplicationException</span> (such as tools from <a rel="external" href="http://www.telerik.com/" title="Telerik">Telerik</a>, <a rel="external" href="http://www.aspose.com/" title="Aspose">Aspose</a>, <a rel="external" href="http://www.llblgen.com/" title="LLBLGen">LLBLGen</a>, Microsoft's <a rel="external" href="http://www.codeplex.com/entlib" title="Codeplex - Enterprise Library">Enterprise Library</a>, <a rel="external" href="http://logging.apache.org/log4net//index.html" title="Log4net">Log4net</a>, <a rel="external" href="http://dev.mysql.com/downloads/connector/net/6.0.html" title="MySQL .NET provider">MySQL</a>, <a rel="external" href="http://www.icsharpcode.net/" title="IC#Code">ICSharpCode</a>, <a rel="external" href="http://www.aspnetemail.com/" title="aspNetMail">aspNetEmail</a>, <a rel="external" href="http://www.html-to-pdf.net/ExpertPDF-HtmlToPdf-Converter.aspx" title="Html-to-pdf">Html-to-pdf</a> and many, many more).<br /><br />That makes catching an <span class="type">ApplicationException</span> so general that I consider it similar to catching the <span class="type">Exception</span> base class. You simply never know what you're catching.<br /><br />While inheriting from <span class="type">ApplicationException</span> itself has no evil in it, the problem starts when you, as a framework or application developer, derive all your exceptions directly from <span class="type">ApplicationException</span>. For instance, a few years ago on a project of one of my clients, the developers defined exceptions that were thrown by the business layer and contained information for the end user. The exceptions were caught at the presentation level and subsequently displayed on the user interface. While there's nothing wrong in doing this, the problem was that these 'end user exceptions' all inherited directly from <span class="type">ApplicationException</span> and the presentation layer caught those <span class="type">ApplicationException</span>s. It&rsquo;s not surprising that once in a while technical exception messages were displayed to the end user. Showing technical information to your users will not only annoy them, it could cause a security risk, because <a rel="external" href="http://www.owasp.org/index.php/Top_10_2007-Information_Leakage_and_Improper_Error_Handling" title="OWASP TOP 10: Information Leakage and Improper Error Handling">you&rsquo;re leaking information</a>.<br /><br />Another client recently went even further. While the developers did actually define their own exception base class for business layer exceptions (which is a good thing), they decided to name it &lsquo;ApplicationException&rsquo;. What they didn&rsquo;t realize that about 75% of the time they actually caught the real <span class="code">System.</span><span class="type">ApplicationException</span> instead of their own business layer exception. This caused all sort of subtle, hard to find bugs. The remedy was to rename the exception and fix all lines were <span class="code">System.</span><span class="type">ApplicationException</span> was caught.<br /><br />While the OR/M mapper framework LLBLGen uses <span class="type">ApplicationException</span>, the design is better than the cases above. LLBLGen defines a base exception (called <span class="type">ORMException</span>) from which all other exceptions inherit. <span class="type">ORMException</span> inherits from <span class="type">ApplicationException</span> and thus all LLBLGen exceptions inherit from it. Catching an LLBLGen exception however, can be done by catching <span class="type">ORMException</span> and therefore it's not a problem that <span class="type">ORMException</span> inherits from <span class="type">ApplicationException</span>. Still, it's useless and while being a breaking change, I still advice LLBLGen to let <span class="type">ORMException</span> directly inherit from <span class="type">Exception</span>. This way LLBLGen exceptions can not accidentally be caught when a application developer catches <span class="type">ApplicationException</span>.<br /><br />If you&rsquo;re maintaining an existing code base, especially the code base of a reusable framework, you have to be careful when making breaking changes, like removing <span class="type">ApplicationException</span> from the inheritance hierarchy. However, when building a new framework or application, just don&rsquo;t use <span class="type">ApplicationException</span>.</p><p>Cheers.</p>
		]]></content>
		<author>
			<name>Steven</name>
		</author>
	</entry>
	
	
	
	<entry>
		<title>Book: Microsoft .NET: Architecting Applications for the Enterprise.</title>
		<link rel="alternate" type="text/html" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=55" />
		<updated>2009-08-18T17:32:00+02:00</updated>
		<published>2009-08-18T17:32:00+02:00</published>
		<id>tag:pivotpowered,2012:NETJunkie.55</id>
		<link rel="related" type="text/html" href=""  />
		<summary type="text">Last month I read Microsoft .NET: Architecting Applications for the Enterprise, written by Dino Esposito and Andrea Saltarello. This book is a great piece of work.</summary>
        <content type="html" xml:lang="en" xml:base="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=55"><![CDATA[
                Last month I read &lsquo;Microsoft .NET: Architecting Applications for the Enterprise&rsquo;, written by Dino Esposito and Andrea Saltarello. This book is a great piece of work.<p><a rel="external" href="http://www.amazon.com/dp/073562609X" title="Amazon.com - Microsoft .NET: Architecting Applications for the ">Microsoft .NET: Architecting Applications for the Enterprise</a> discusses many design principles and applies them to the .NET space. There are a wide range of concepts, patterns, and technologies discussed. The book discusses the layers of a default architecture, such as <a rel="external" href="http://en.wikipedia.org/wiki/Data_access_layer" title="Wikipedia - Data access layer">Data Access Layer</a>, <a rel="external" href="http://en.wikipedia.org/wiki/Business_layer" title="Wikipedia - Business logic layer">Business Layer</a>, <a rel="external" href="http://en.wikipedia.org/wiki/Service_layer" title="Wikipedia - Service layer">Service Layer</a>, and Presentation Layer. Each of these layers are discussed in their own chapter and relevant patterns and practices are discussed with each layer.<br /><br />The book discusses concepts like: <a rel="external" href="http://en.wikipedia.org/wiki/Separation_of_concerns" title="Wikipedia - Separation of concerns">Separation of Concerns</a>, the <a rel="external" href="http://en.wikipedia.org/wiki/Open/closed_principle" title="Wikipedia - Open/closed principle">Open/Closed Principle</a>, <a rel="external" href="http://en.wikipedia.org/wiki/Liskov_substitution_principle" title="Wikipedia - Liskov substitution principle">Liskov Substitution Principle</a>, <a rel="external" href="http://en.wikipedia.org/wiki/Object_Relational_Mapping" title="Wikipedia - Object-relational mapping">Object-Relational Mapping</a>, and <a rel="external" href="http://en.wikipedia.org/wiki/Aspect_Oriented_Programming" title="Wikipedia - Aspect-oriented programming">Aspect-Oriented Programming</a>. The book also discusses patterns such as <a rel="external" href="http://martinfowler.com/eaaCatalog/transactionScript.html" title="Martin Fowler - Transaction Script">Transaction Script</a>, <a rel="external" href="http://martinfowler.com/eaaCatalog/tableModule.html" title="Martin Fowler - Table Module">Table Module</a>, <a rel="external" href="http://en.wikipedia.org/wiki/Active_record_pattern" title="Wikipedia - Active record pattern">Active Record</a>, <a rel="external" href="http://en.wikipedia.org/wiki/Domain-driven_design" title="Wikipedia - Domain-driven design">Domain Model</a>, <a rel="external" href="http://en.wikipedia.org/wiki/Data_transfer_object" title="Wikipedia - Data Transfer Object">Data Transfer Object</a>, <a rel="external" href="http://en.wikipedia.org/wiki/Inversion_of_control" title="Wikipedia - Inversion of control">Inversion of Control</a>, <a rel="external" href="http://nl.wikipedia.org/wiki/Model-view-controller-model" title="Wikipedia - Model-view-controller-model">Model-View-Controller</a>, and <a rel="external" href="http://en.wikipedia.org/wiki/Model-view-presenter" title="Wikipedia - Model-view-presenter">Model-View-Presenter</a>.<br /><br />A lot of the subjects, frameworks and patterns in this book deserve a book of their own, therefore the book doesn&rsquo;t discuss most of them in-depth, but this -in my opinion- is actually the beauty of the book; most of the time it discusses just enough to get a good picture of the considerations you will have to make as an architect. It gives you a great start for further exploration.<br /><br />What I especially like about the book is the discussion on topics like the Domain Model and Data Transfer Objects. <a rel="external" href="http://weblogs.asp.net/despos/" title="Dino Esposito's weblog">Dino</a> and <a rel="external" href="http://www.linkedin.com/pub/andrea-saltarello/5/337/228" title="LinkedIn - Andrea Saltarello">Andrea</a> discuss the Domain Model Pattern and do a good job in explaining the difficulties with it. I&rsquo;ve read <a rel="external" href="http://jimmynilsson.com/blog/" title="Jimmy Nilsson's Weblog">Jimmy Nilsson</a>&rsquo;s <a rel="external" href="http://www.amazon.com/exec/obidos/ASIN/0321268202" title="Amazon - Applying Domain-Driven Design and Patterns: With Examples in C# and .NET">book about Domain-Driven Design</a>. While I love Jimmy&rsquo;s book, he never discussed the Domain Model&rsquo;s tradeoffs, Architecting Applications for the Enterprise actually does explain this. The bottom line is: Domain Model isn't suited for every organization; you should choose wisely and Dino and Andrea help you to make that decision.<br /><br />With the use of Data Transfer Objects (DTO), the writers explain that DTOs are good for separating the Domain layer from the Presentation layer, but also warn that &quot;<em>In large projects with so many entities, DTOs add a remarkable level of (extra) complexity and work to do</em>&quot;. <a rel="external" href="http://msdn.microsoft.com/nl-nl/magazine/ee236638%28en-us%29.aspx" title="MSDN Magazine - Pros and Cons of Data Transfer Objects">Dino's recent MSDN article</a> is basically a summary of that discussion in the book.<br /><br />I had one big annoyance with the book though, which is it&rsquo;s extensive use of acronyms. For instance, after discussing a new pattern, such as Transaction Script, Table Module, Active Record, or Domain Model (and many more), the remainder of the book referred to their acronyms TS, TM, AR, and DM. More than once I had to go back many pages to figure out what a certain acronym meant.<br /><br />My final conclusion is that this is a great book. In case you want to know more about architecture applied to .NET concepts, you&rsquo;d better start reading this book!</p><p style="text-align:center;"><img src="http://www.cuttingedge.it/blogs/steven/images/architecting_applications_for_the_enterprise.jpg" style="border:0px solid" title="Microsoft .NET" alt="Microsoft .NET" class="pivot-image" /></p>
		]]></content>
		<author>
			<name>Steven</name>
		</author>
	</entry>
	
	
	
	<entry>
		<title>Free C# 3.0 Pocket Reference ebook</title>
		<link rel="alternate" type="text/html" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=54" />
		<updated>2010-01-14T12:33:00+02:00</updated>
		<published>2009-08-17T10:27:00+02:00</published>
		<id>tag:pivotpowered,2012:NETJunkie.54</id>
		<link rel="related" type="text/html" href=""  />
		<summary type="text">Just found this free ebook on the Red Gate site:</summary>
        <content type="html" xml:lang="en" xml:base="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=54"><![CDATA[
                Just found this free ebook on the <a rel="external" href="http://www.red-gate.com" title="Red Gate">Red Gate</a> site:<blockquote>This book is for busy programmers who want a succinct and yet readable guide to C# 3.0 and LINQ.<br /> C# 3.0 Pocket Reference, written by Joseph and Ben Albahari, tells you exactly what you need to know, without long introductions or bloated samples. Boost your C# expertise and keep ahead of your peers! <a rel="external" href="http://www.red-gate.com/products/ants_performance_profiler/be_ahead_of_the_game_ebook.htm?utm_source=simpletalk&amp;utm_medium=email&amp;utm_content=nlv_aheadofgame-ebook&amp;utm_campaign=antsperformanceprofiler" title="Red Gate - Free ebook on C# 3.0">-&gt;</a><br /></blockquote><p>Download it here: <a rel="external" href="http://downloads.red-gate.com/ebooks/DotNet/Csharp3_Pocket_Reference_Second_Edition.zip" title="C# Pocket Reference Second Edition pdf">C# Pocket Reference Second Edition</a></p><p><font color="#ff0000">UPDATE: </font>Sorry, the pocket reference can not be downloaded from the Red Gate site anymore. But with a bit of smart googling, you might still find it.</p>
		]]></content>
		<author>
			<name>Steven</name>
		</author>
	</entry>
	
	
	
	<entry>
		<title>Choosing FxCop rules for Line Of Business applications</title>
		<link rel="alternate" type="text/html" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=53" />
		<updated>2009-08-16T11:09:00+02:00</updated>
		<published>2009-08-16T11:09:00+02:00</published>
		<id>tag:pivotpowered,2012:NETJunkie.53</id>
		<link rel="related" type="text/html" href=""  />
		<summary type="text">Dennis Doomen, architect at Aviva Solutions, published a set of C# 3.0 Coding Guidelines a few months ago. While a lot of different C# coding guidelines can be found on the web, this one caught my attention.</summary>
        <content type="html" xml:lang="en" xml:base="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=53"><![CDATA[
                <a rel="external" href="http://www.dennisdoomen.net" title="Dennis Doomen's weblog">Dennis Doomen</a>, architect at <a rel="external" href="http://www.avivasolutions.nl/" title="Aviva Solutions">Aviva Solutions</a>, <a rel="external" href="http://www.dennisdoomen.net/2009/03/new-coding-guidelines-for-c-30.html" title="Dennis Doomen's weblog - New coding guidelines for C# 3.0">published</a> a set of C# 3.0 Coding Guidelines a few months ago. While a lot of different C# coding guidelines can be found on the web, this one caught my attention.The last four pages of the <a rel="external" href="http://blog.avivasolutions.nl/Attachments/AvSol%20CSharp%203.0%20Coding%20Guidelines.pdf" title="C# 3.0 Coding Guidelines Guidelines for .NET development">document</a> consist of the list of <a rel="external" href="http://msdn.microsoft.com/en-us/library/bb429476%28VS.80%29.aspx" title="MSDN - FxCop">Microsoft Code Analysis</a> (a.k.a. FxCop) rules. What makes this list great is that Dennis made a distinction between two types of .NET code bases, namely: <a rel="external" href="http://en.wikipedia.org/wiki/Line_of_Business" title="Wikipedia - Line of business">Line Of Business</a> (LOB) applications and reusable Frameworks. Because FxCop was primarily written to validate the .NET framework itself, it focuses on validating reusable frameworks. We could therefore expect most FxCop rules to hold especially for frameworks. For LOB applications however, not all rules apply. Dennis recognized this and made a distinction between the two types.<br /><br />I've seen organizations struggle with choosing FxCop rules. In my opinion this list is a great way to get started.
		]]></content>
		<author>
			<name>Steven</name>
		</author>
	</entry>
	
	
	
</feed>

