<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Elegant Code &#187; Jarod Ferguson</title>
	<atom:link href="http://elegantcode.com/author/ferguson/feed/" rel="self" type="application/rss+xml" />
	<link>http://elegantcode.com</link>
	<description></description>
	<lastBuildDate>Sat, 13 Mar 2010 01:26:34 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.6</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Event Driven Architecture: Publishing Events using an IOC container</title>
		<link>http://elegantcode.com/2010/01/06/event-driven-architecture-publishing-events-using-an-ioc-container/</link>
		<comments>http://elegantcode.com/2010/01/06/event-driven-architecture-publishing-events-using-an-ioc-container/#comments</comments>
		<pubDate>Thu, 07 Jan 2010 00:29:27 +0000</pubDate>
		<dc:creator>Jarod Ferguson</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Event Driven Architecture]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/01/06/event-driven-architecture-publishing-events-using-an-ioc-container/</guid>
		<description><![CDATA[In my last post I talked about advanced IOC usage and how it is possible to use an IOC container to resolve an open generic from a closed implementation. This is technically cool, but it does not explain why this is important. In this post I want to show some additional code that will demonstrate [...]]]></description>
			<content:encoded><![CDATA[<p>In <a href="http://elegantcode.com/2009/12/18/advanced-unity-connecting-implementations-to-open-generic-types/">my last post</a> I talked about advanced IOC usage and how it is possible to use an IOC container to resolve an open generic from a closed implementation. This is technically cool, but it does not explain why this is important. In this post I want to show some additional code that will demonstrate a basic concept of <a href="http://en.wikipedia.org/wiki/Event_Driven_Architecture">Event Driven Architecture</a>: Publishing an Event.</p>
<p>&#160;</p>
<h4>Why is Event Driven Architecture good?</h4>
<p>Event driven architecture is extremely extensible. <strong>In my mind, it the perfect solution to address the <a href="http://en.wikipedia.org/wiki/Open/closed_principle">Open Closed Principal</a> and enable <a href="http://en.wikipedia.org/wiki/Single_responsibility_principle">Single Responsibility</a> in code</strong>. </p>
<p>Consider a system that processes orders. There is a method called SubmitOrder(order) on an OrderController. It just validates and saves the new order to the database today.</p>
<p>In a following story, the product owner says “<strong>I need the system to send an email to the customer when the order is submitted</strong>”. No problem, inject the MailService into the OrderController, send the mail in the SubmitOrder(order) method. great.</p>
<p>The next story the product owner says “<strong>I need you to deduct the ordered quantities from the OnHand inventory</strong>”. Check, so we inject in the inventory service into our OrderController, and we call it from the SubmitOrder(order) method.</p>
<p>More stories…. the product owner says “<strong>We need to send a message to the warehouse fulfillment system to let them know a new order has been submitted</strong>” </p>
<p>Ugh, another service, another method. The tests for SubmitOrder become out of control. Even when extracting methods and encapsulating more logic into services, there is still violation of SRP &amp; OCP. Not to mention there could be performance degradation from performing all of these tasks synchronously while the user waits. </p>
<p><strong>Its not the job of SubmitOrder to do all of this, there has to be a better way.</strong></p>
<p>&#160;</p>
<h4>Publishing an Event Example</h4>
<p>What if I “<strong>tell</strong>” the system that an event had occurred, and anyone interested could take action? (like an old school observer right?) In the following code sample I am going to inject in an ‘EventPublisher’ into my OrderController, then use that object to notify the rest of the system by publishing an <a href="http://www.eaipatterns.com/EventMessage.html">event</a> using this line:</p>
<div>
<div class="csharpcode">
<pre class="alt">_eventPublisher.Publish(<span class="kwrd">new</span> OrderSubmittedEvent{OrderId = order.Id});</pre>
</p></div>
</div>
<h6>&#160;</h6>
<h6>The OrderController</h6>
<div>
<div class="csharpcode">
<pre class="alt"><span class="kwrd">public</span> <span class="kwrd">class</span> OrderController : Controller</pre>
<pre class="alteven">{</pre>
<pre class="alt">   <span class="kwrd">private</span> <span class="kwrd">readonly</span> IRepository&lt;Order&gt; _orderRepository;</pre>
<pre class="alteven">   <span class="kwrd">private</span> <span class="kwrd">readonly</span> IEventPublisher _eventPublisher;</pre>
<pre class="alt">&#160;</pre>
<pre class="alteven">   <span class="kwrd">public</span> OrderController(IRepository&lt;Order&gt; orderRepository, </pre>
<pre class="alt">                          IEventPublisher eventPublisher)</pre>
<pre class="alteven">   {</pre>
<pre class="alt">       _orderRepository = orderRepository;</pre>
<pre class="alteven">       _eventPublisher = eventPublisher;</pre>
<pre class="alt">   }</pre>
<pre class="alteven">&#160;</pre>
<pre class="alt">   <span class="kwrd">public</span> ActionResult SubmitOrder(OrderViewModel viewModel)</pre>
<pre class="alteven">   {</pre>
<pre class="alt">       <span class="kwrd">try</span></pre>
<pre class="alteven">       {</pre>
<pre class="alt">           <span class="kwrd">if</span> (ModelState.IsValid)</pre>
<pre class="alteven">           {</pre>
<pre class="alt">               var order = MapOrder(viewModel);</pre>
<pre class="alteven">               _orderRepository.Add(order);</pre>
<pre class="alt">               _orderRepository.SaveChanges();</pre>
<pre class="alteven">&#160;</pre>
<pre class="alt">               _eventPublisher.Publish(<span class="kwrd">new</span> OrderSubmittedEvent{OrderId = order.Id});</pre>
<pre class="alteven">             </pre>
<pre class="alt">               <span class="rem">//Display success message</span></pre>
<pre class="alteven">               <span class="rem">//ViewInfo.AddSuccessMessage(Language.SubmitOrderSuccess);</span></pre>
<pre class="alt">           }</pre>
<pre class="alteven">       }</pre>
<pre class="alt">       <span class="kwrd">catch</span></pre>
<pre class="alteven">       {</pre>
<pre class="alt">           ModelState.AddModelError(<span class="str">&quot;__Form&quot;</span>, Language.SubmitOrderError);</pre>
<pre class="alteven">       }</pre>
<pre class="alt">  </pre>
<pre class="alteven">       <span class="kwrd">return</span> View(viewModel);</pre>
<pre class="alt">   }</pre>
<pre class="alteven">&#160;</pre>
<pre class="alt">   <span class="rem">//other</span></pre>
<pre class="alteven">}</pre>
</p></div>
</div>
<p>&#160;</p>
<p>Now, using this simple <a href="http://www.eaipatterns.com/EventDrivenConsumer.html">Consumer</a> (Handler) interface:</p>
<div>
<div class="csharpcode">
<pre class="alt"><span class="kwrd">public</span> <span class="kwrd">interface</span> IConsumer&lt;T&gt;</pre>
<pre class="alteven">{</pre>
<pre class="alt">    <span class="kwrd">void</span> Handle(T eventMessage);</pre>
<pre class="alteven">}</pre>
</p></div>
</div>
<p>&#160;</p>
<p>I can independently implement each of the system requirements, as needed:</p>
<div>
<div class="csharpcode">
<pre class="alt"><span class="kwrd">public</span> <span class="kwrd">class</span> EmailOrderConfirmation : IConsumer&lt;OrderSubmittedEvent&gt;</pre>
<pre class="alteven">{</pre>
<pre class="alt">   <span class="kwrd">public</span> <span class="kwrd">void</span> Handle(OrderSubmittedEvent eventMessage)</pre>
<pre class="alteven">   {</pre>
<pre class="alt">      <span class="rem">//send email</span></pre>
<pre class="alteven">   }</pre>
<pre class="alt">}</pre>
<pre class="alteven">&#160;</pre>
<pre class="alt"><span class="kwrd">public</span> <span class="kwrd">class</span> NotifyWarehouse : IConsumer&lt;OrderSubmittedEvent&gt;</pre>
<pre class="alteven">{</pre>
<pre class="alt">   <span class="kwrd">public</span> <span class="kwrd">void</span> Handle(OrderSubmittedEvent eventMessage)</pre>
<pre class="alteven">   {</pre>
<pre class="alt">       <span class="rem">//notify warehouse</span></pre>
<pre class="alteven">   }</pre>
<pre class="alt">}</pre>
<pre class="alteven">&#160;</pre>
<pre class="alt"><span class="kwrd">public</span> <span class="kwrd">class</span> DeductOnHandInventory : IConsumer&lt;OrderSubmittedEvent&gt;</pre>
<pre class="alteven">{</pre>
<pre class="alt">   <span class="kwrd">public</span> <span class="kwrd">void</span> Handle(OrderSubmittedEvent eventMessage)</pre>
<pre class="alteven">   {</pre>
<pre class="alt">       <span class="rem">//deduct inventory</span></pre>
<pre class="alteven">   }</pre>
<pre class="alt">}</pre>
</p></div>
</div>
<p>&#160;</p>
<p>One of my favorite parts about this code: <strong>the container is building up all of these event consumers, which makes it is easy to satisfy all of the dependencies using constructor injection.</strong> This makes testing each of these handlers a breeze, and everything follows the same patterns and conventions keeping the code base understandable and clean. (Services, Controllers, Consumers all work the same)</p>
<p>Just plug in the dependencies in the EmailOrderConfirmation consumer ctor* like so:</p>
<div>
<div class="csharpcode">
<pre class="alt"><span class="kwrd">public</span> <span class="kwrd">class</span> EmailOrderConfirmation : IConsumer&lt;OrderSubmittedEvent&gt;</pre>
<pre class="alteven">{</pre>
<pre class="alt">   <span class="kwrd">private</span> <span class="kwrd">readonly</span> IRepository&lt;Order&gt; _orderRepository;</pre>
<pre class="alteven">   <span class="kwrd">private</span> <span class="kwrd">readonly</span> ISmtpService _smtpService;</pre>
<pre class="alt">   <span class="kwrd">private</span> <span class="kwrd">readonly</span> ILogger _logger;</pre>
<pre class="alteven">&#160;</pre>
<pre class="alt">   <span class="kwrd">public</span> EmailOrderConfirmation(IRepository&lt;Order&gt; orderRepository, </pre>
<pre class="alteven">                                 ISmtpService smtpService,</pre>
<pre class="alt">                                 ILogger logger)</pre>
<pre class="alteven">   {</pre>
<pre class="alt">       _orderRepository = orderRepository;</pre>
<pre class="alteven">       _smtpService = smtpService;</pre>
<pre class="alt">       _logger = logger;</pre>
<pre class="alteven">   }</pre>
<pre class="alt">&#160;</pre>
<pre class="alteven">   <span class="kwrd">public</span> <span class="kwrd">void</span> Handle(OrderSubmittedEvent eventMessage)</pre>
<pre class="alt">   {</pre>
<pre class="alteven">       var order = _orderRepository.Single(x =&gt; x.Id == eventMessage.OrderId);</pre>
<pre class="alt">       var message = <span class="kwrd">new</span> SmtpMessage();</pre>
<pre class="alteven">       <span class="rem">//get customer info from order  &amp; populate message</span></pre>
<pre class="alt">       _smtpService.SendMessage(message);</pre>
<pre class="alteven">   }</pre>
<pre class="alt">}</pre>
</p></div>
</div>
<p><strong></strong></p>
<p><strong>* Note that you could also inject the IEventPublisher into a Consumer and publish more events. </strong></p>
<p><strong></strong></p>
<h4>&#160;</h4>
<h4>How Does it Work?</h4>
<p>Under the hood the IoC container is doing most of the work. It keeps track of the event subscriptions and also provides the consumer instantiation. </p>
<h5>Event Subscriptions</h5>
<p>Here is how the event subscriptions are added to the container. In this example I use an interface so that I can enable dependency injection into components, and then mock the GetSubscriptions&lt;T&gt; dependency for easy testing. I also use a static method for adding subscriptions since the registration process operation usually happens at bootstrapping time, which is generally all static. The IoC.Container here is thread safe. </p>
<div>
<div class="csharpcode">
<pre class="alt"><span class="kwrd">public</span> <span class="kwrd">interface</span> ISubscriptionService</pre>
<pre class="alteven">{</pre>
<pre class="alt">   IEnumerable&lt;IConsumer&lt;T&gt;&gt; GetSubscriptions&lt;T&gt;();</pre>
<pre class="alteven">}</pre>
<pre class="alt">&#160;</pre>
<pre class="alteven"><span class="kwrd">public</span> <span class="kwrd">class</span> EventSubscriptions : ISubscriptionService</pre>
<pre class="alt">{</pre>
<pre class="alteven">   <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">void</span> Add&lt;T&gt;()</pre>
<pre class="alt">   {</pre>
<pre class="alteven">       var consumerType = <span class="kwrd">typeof</span>(T);</pre>
<pre class="alt">&#160;</pre>
<pre class="alteven">       consumerType.GetInterfaces()</pre>
<pre class="alt">                   .Where(x =&gt; x.IsGenericType)</pre>
<pre class="alteven">                   .Where(x =&gt; x.GetGenericTypeDefinition() == <span class="kwrd">typeof</span>(IConsumer&lt;&gt;))</pre>
<pre class="alt">                   .ToList()</pre>
<pre class="alteven">                   .ForEach(x =&gt; IoC.Container.RegisterType(x, </pre>
<pre class="alt">                                                            consumerType, </pre>
<pre class="alteven">                                                            consumerType.FullName));</pre>
<pre class="alt">   }</pre>
<pre class="alteven">&#160;</pre>
<pre class="alt">   <span class="kwrd">public</span> IEnumerable&lt;IConsumer&lt;T&gt;&gt; GetSubscriptions&lt;T&gt;()</pre>
<pre class="alteven">   {</pre>
<pre class="alt">       var consumers =  IoC.Container.ResolveAll(<span class="kwrd">typeof</span>(IConsumer&lt;T&gt;));</pre>
<pre class="alteven">       <span class="kwrd">return</span> consumers.Cast&lt;IConsumer&lt;T&gt;&gt;();</pre>
<pre class="alt">   }</pre>
<pre class="alteven">}</pre>
</p></div>
</div>
<p>&#160;</p>
<h5>Event Publishing</h5>
<p>Now that the subscriptions are setup, the publisher can read those subscriptions, get the consumers from the container, and pass the event message instance to each of them. Again I am using an Interface so I can enable dependency injection (and mocking capabilities) for the components which need to do publishing (controllers, services)</p>
<div>
<div class="csharpcode">
<pre class="alt"><span class="kwrd">public</span> <span class="kwrd">interface</span> IEventPublisher</pre>
<pre class="alteven">{</pre>
<pre class="alt">   <span class="kwrd">void</span> Publish&lt;T&gt;(T eventMessage);</pre>
<pre class="alteven">}</pre>
<pre class="alt">&#160;</pre>
<pre class="alteven"><span class="kwrd">public</span> <span class="kwrd">class</span> EventPublisher : IEventPublisher</pre>
<pre class="alt">{</pre>
<pre class="alteven">   <span class="kwrd">private</span> <span class="kwrd">readonly</span> ISubscriptionService _subscriptionService;</pre>
<pre class="alt">&#160;</pre>
<pre class="alteven">   <span class="kwrd">public</span> EventPublisher(ISubscriptionService subscriptionService)</pre>
<pre class="alt">   {</pre>
<pre class="alteven">       _subscriptionService = subscriptionService;</pre>
<pre class="alt">   }</pre>
<pre class="alteven">&#160;</pre>
<pre class="alt">   <span class="kwrd">public</span> <span class="kwrd">void</span> Publish&lt;T&gt;(T eventMessage)</pre>
<pre class="alteven">   {</pre>
<pre class="alt">       var subscriptions = _subscriptionService.GetSubscriptions&lt;T&gt;();</pre>
<pre class="alteven">       subscriptions.ToList().ForEach(x =&gt; PublishToConsumer(x, eventMessage));</pre>
<pre class="alt">   }</pre>
<pre class="alteven">&#160;</pre>
<pre class="alt">   <span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">void</span> PublishToConsumer&lt;T&gt;(IConsumer&lt;T&gt; x, T eventMessage)</pre>
<pre class="alteven">   {</pre>
<pre class="alt">       <span class="kwrd">try</span></pre>
<pre class="alteven">       {</pre>
<pre class="alt">           x.Handle(eventMessage);</pre>
<pre class="alteven">       }</pre>
<pre class="alt">       <span class="kwrd">catch</span>(Exception e)</pre>
<pre class="alteven">       {</pre>
<pre class="alt">           <span class="rem">//log and handle internally</span></pre>
<pre class="alteven">       }</pre>
<pre class="alt">       <span class="kwrd">finally</span></pre>
<pre class="alteven">       {</pre>
<pre class="alt">           var instance = x <span class="kwrd">as</span> IDisposable;</pre>
<pre class="alteven">           <span class="kwrd">if</span> (instance != <span class="kwrd">null</span>)</pre>
<pre class="alt">           {</pre>
<pre class="alteven">               instance.Dispose();</pre>
<pre class="alt">           }</pre>
<pre class="alteven">       }</pre>
<pre class="alt">   }</pre>
<pre class="alteven">}</pre>
</p></div>
</div>
<p>&#160;</p>
<p>- <strong>Keep in mind in this example is all running on the same thread, therefore even though semantically we are handling events as if they are asynchronous, it is a blocking operation</strong></p>
<p>&#160;</p>
<h4>Additional Benefits of this Architecture</h4>
<p>- Events are in messages, which can be serialized and processed on different threads, or even different nodes in a cluster. In a web environment, this might mean offloading the workload out of your IIS processes freeing web-server threads for performance &amp; scalability (see Service Bus section)</p>
<p>- Get multicast delegate observer like functionality without having to deal with static events, event registration &amp; deregistration (the whole += –= biz)</p>
<p>- Each event handler has its own class, each having 1 responsibility</p>
<p>- Very extensible, very maintainable (wait, I said that already?)</p>
<p>&#160;</p>
<h5></h5>
<h5></h5>
<h5></h5>
<h4>This is not a Service Bus</h4>
<p>This code above could work great in a simple MVC.NET application for implementing clean separation and structuring your code base into events. Though it gets a lot of influence from the OSS services busses, it is greatly simplified and merely demonstrates a simple concept of publishing &amp; consuming domain events using an IoC container.</p>
<p>A service bus does quite a bit more than just publishing local messages on single thread. If you find yourself enjoying this posts and want to take it to the next level, check out <a href="http://code.google.com/p/masstransit/">MassTransit</a> (Chris Patterson &amp; Dru Sellers) &amp; <a href="http://www.nservicebus.com/">nServiceBus</a> (Udi Dahan). I would also recommend the <a href="http://www.eaipatterns.com/eaipatterns.html">EAI patterns</a> books by Gregor Hohpe and recognize the <a href="http://www.eaipatterns.com/toc.html">reference patterns</a>. (one of these days Ill make it through it instead of using it for reference!)</p>
<p>Some additional concepts and common patterns you might find: </p>
<ul>
<li><a href="http://en.wikipedia.org/wiki/Publish/subscribe">Publish-Subscribe</a> </li>
<li><a href="http://en.wikipedia.org/wiki/Request-response">Request-Response</a> </li>
<li><a href="http://www.udidahan.com/2009/04/20/saga-persistence-and-event-driven-architectures/">Sagas (Workflow)</a> </li>
<li><a href="http://masstransit.pbworks.com/MessageCorrelation">Correlation</a> </li>
<li><a href="http://www.eaipatterns.com/CompetingConsumers.html">Competing Consumers</a> </li>
<li><a href="http://artofbabel.com/specials/73-distributed-processing-with-nservicebus.html">Distributed Load</a> (processing across many nodes in cluster) </li>
<li>Transport (Http, MSMQ, ActiveMq, WCF TCP) </li>
<li>Serialization (Binary, XML, JSON) </li>
<li>Threadpooling </li>
</ul>
<ul></ul>
<h4>The Specification</h4>
</p>
</p>
</p>
</p>
</p>
</p>
<p>Normally I don&#8217;t make a habit of testing the container, but in this case its so close to the container I feel its appropriate vs mocking out the subscriptions. Plus since this is a blog post demonstrating advanced IOC usage, I want explicitly show all of the dependencies required at bootstrap time.</p>
<p>Please note the LoggerSpy for assertions. In this spec we are really only concerned whether or not they get called. Because of the nature of eventing, using a <a href="http://xunitpatterns.com/Test%20Spy.html">Test Spy</a> is really the only good way I have found to assert whether or not your handlers get invoked. (<em>If your processing on multiple threads you will have to make sure they are all done before you check assertions, perhaps a future blog post)</em></p>
<div>
<div class="csharpcode">
<pre class="alt">[TestFixture]</pre>
<pre class="alteven"><span class="kwrd">public</span> <span class="kwrd">class</span> When_An_Order_Is_Submitted : Specification_Context</pre>
<pre class="alt">{</pre>
<pre class="alteven">   <span class="kwrd">private</span> LoggerSpy _loggerSpy;</pre>
<pre class="alt">   <span class="kwrd">private</span> Mock&lt;IRepository&lt;Order&gt;&gt; _orderRepositoryMock;</pre>
<pre class="alteven">   <span class="kwrd">readonly</span> IUnityContainer _container = IoC.Container;</pre>
<pre class="alt">&#160;</pre>
<pre class="alteven">   <span class="kwrd">protected</span> <span class="kwrd">override</span> <span class="kwrd">void</span> Context()</pre>
<pre class="alt">   {</pre>
<pre class="alteven">       <span class="rem">//setup EF repository mock</span></pre>
<pre class="alt">       _orderRepositoryMock = <span class="kwrd">new</span> Mock&lt;IRepository&lt;Order&gt;&gt;();</pre>
<pre class="alteven">&#160;</pre>
<pre class="alt">       <span class="rem">//logger spy to capture handler messages</span></pre>
<pre class="alteven">       _loggerSpy = <span class="kwrd">new</span> LoggerSpy();</pre>
<pre class="alt">&#160;</pre>
<pre class="alteven">       <span class="rem">//register with container</span></pre>
<pre class="alt">       _container.RegisterInstance&lt;ILogger&gt;(_loggerSpy);</pre>
<pre class="alteven">       _container.RegisterInstance(_orderRepositoryMock.Object);</pre>
<pre class="alt">       _container.RegisterType&lt;IEventPublisher, EventPublisher&gt;();</pre>
<pre class="alteven">       _container.RegisterType&lt;ISubscriptionService, EventSubscriptions&gt;();</pre>
<pre class="alt">       _container.RegisterType&lt;OrderController&gt;();</pre>
<pre class="alteven">&#160;</pre>
<pre class="alt">       <span class="rem">//add event subscriptions</span></pre>
<pre class="alteven">       EventSubscriptions.Add&lt;EmailOrderConfirmation&gt;();</pre>
<pre class="alt">       EventSubscriptions.Add&lt;NotifyWarehouse&gt;();</pre>
<pre class="alteven">       EventSubscriptions.Add&lt;DeductOnHandInventory&gt;();</pre>
<pre class="alt">   }</pre>
<pre class="alteven">&#160;</pre>
<pre class="alt">   <span class="kwrd">protected</span> <span class="kwrd">override</span> <span class="kwrd">void</span> Because()</pre>
<pre class="alteven">   {</pre>
<pre class="alt">       _container.Resolve&lt;OrderController&gt;().SubmitOrder(<span class="kwrd">new</span> OrderViewModel());</pre>
<pre class="alteven">   }</pre>
<pre class="alt">&#160;</pre>
<pre class="alteven">   [Test]</pre>
<pre class="alt">   <span class="kwrd">public</span> <span class="kwrd">void</span> Order_Should_Be_Persisted()</pre>
<pre class="alteven">   {</pre>
<pre class="alt">       _orderRepositoryMock.Verify(x =&gt; x.Add(It.IsAny&lt;Order&gt;()));</pre>
<pre class="alteven">       _orderRepositoryMock.Verify(x =&gt; x.SaveChanges());</pre>
<pre class="alt">   }</pre>
<pre class="alteven">&#160;</pre>
<pre class="alt">   [Test]</pre>
<pre class="alteven">   <span class="kwrd">public</span> <span class="kwrd">void</span> Email_Notification_Should_Be_Sent_To_Customer()</pre>
<pre class="alt">   {</pre>
<pre class="alteven">       _loggerSpy.LoggedMessages.ShouldContain(Language.OrderConfirmationEmailSuccess);</pre>
<pre class="alt">   }</pre>
<pre class="alteven">&#160;</pre>
<pre class="alt">   [Test]</pre>
<pre class="alteven">   <span class="kwrd">public</span> <span class="kwrd">void</span> On_Hand_Inventory_Should_Be_Reduced()</pre>
<pre class="alt">   {</pre>
<pre class="alteven">       _loggerSpy.LoggedMessages.ShouldContain(Language.DeductOnHandInventorySuccess);</pre>
<pre class="alt">   }</pre>
<pre class="alteven">&#160;</pre>
<pre class="alt">   [Test]</pre>
<pre class="alteven">   <span class="kwrd">public</span> <span class="kwrd">void</span> Warehouse_Should_Be_Notified()</pre>
<pre class="alt">   {</pre>
<pre class="alteven">       _loggerSpy.LoggedMessages.ShouldContain(Language.NotifyWarehouseSuccess);</pre>
<pre class="alt">   }</pre>
<pre class="alteven">}</pre>
</p></div>
</div>
]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/01/06/event-driven-architecture-publishing-events-using-an-ioc-container/feed/</wfw:commentRss>
		<slash:comments>32</slash:comments>
		</item>
		<item>
		<title>Advanced Unity: Connecting Implementations to Open Generic Types</title>
		<link>http://elegantcode.com/2009/12/18/advanced-unity-connecting-implementations-to-open-generic-types/</link>
		<comments>http://elegantcode.com/2009/12/18/advanced-unity-connecting-implementations-to-open-generic-types/#comments</comments>
		<pubDate>Fri, 18 Dec 2009 23:46:47 +0000</pubDate>
		<dc:creator>Jarod Ferguson</dc:creator>
				<category><![CDATA[Esoterica]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/12/18/advanced-unity-connecting-implementations-to-open-generic-types/</guid>
		<description><![CDATA[Jimmy Bogard has an excellent post called “Advanced StructureMap: connecting implementations to open generic types” which he uses the StructureMap IOC container to connect messages to handlers. 
This is something I have been using in my codebase to handle domain events, as well as a publish/subscribe mechanism for WCF message handling. I learned about this [...]]]></description>
			<content:encoded><![CDATA[<p>Jimmy Bogard has an excellent post called “<a href="http://www.lostechies.com/blogs/jimmy_bogard/archive/2009/12/17/advanced-structuremap-connecting-implementations-to-open-generic-types.aspx">Advanced StructureMap: connecting implementations to open generic types</a>” which he uses the <a href="http://structuremap.sourceforge.net/Default.htm">StructureMap</a> IOC container to connect messages to handlers. </p>
<p>This is something I have been using in my codebase to handle domain events, as well as a publish/subscribe mechanism for WCF message handling. I learned about this Handler&lt;T&gt;(or Consumer&lt;T&gt;) approach from the <a href="http://code.google.com/p/masstransit/wiki/MassTransit">MassTransit</a> codebase. For those that don&#8217;t know about MassTransit, it is lean service bus implementation for building loosely coupled applications using the .NET framework. I highly recommend checking it out.</p>
<p>Though I am a big fan of StructureMap, I have also use the <a href="http://www.codeplex.com/unity/">Unity dependency injection container</a> to resolve my handlers/consumers.</p>
<p>&#160;</p>
<h4>The Open Generic Handler</h4>
<p>As Jimmy described in his post, there is an generic interface describing a contract </p>
<div>
<div class="csharpcode">
<pre class="alt"><span class="kwrd">public</span> <span class="kwrd">interface</span> IHandler&lt;TEvent&gt; </pre>
<pre class="alteven">{</pre>
<pre class="alt">    <span class="kwrd">void</span> Handle(TEvent args);</pre>
<pre class="alteven">}</pre>
</p></div>
</div>
</p>
<h4>The Implementation</h4>
<p>The interface is implemented specifying the type (the Domain Event) for the interface contract</p>
<div>
<div class="csharpcode">
<pre class="alt"><span class="kwrd">public</span> <span class="kwrd">class</span> OrderCanceledEvent</pre>
<pre class="alteven">    : IHandler&lt;OrderCanceledMessage&gt;</pre>
<pre class="alt">{</pre>
<pre class="alteven">    <span class="kwrd">public</span> <span class="kwrd">void</span> Handle(OrderCanceledMessage args)</pre>
<pre class="alt">    {</pre>
<pre class="alteven">        <span class="rem">// send an email or something</span></pre>
<pre class="alt">    }</pre>
<pre class="alteven">}</pre>
</p></div>
</div>
<h4>Resolving the Handler</h4>
</p>
<p>When a given domain event occurs, the handler(s) is resolved for the given event, the “T”, or OrderCancelledMessage.</p>
<div>
<div class="csharpcode">
<pre class="alt">var handler = container.Resolve&lt;IHandler&lt;OrderCanceledMessage&gt;&gt;();</pre>
</p></div>
</div>
</p>
<h4>Configuring Unity</h4>
<p>There are a few ways to do this with Unity. I will show how to do it using a Unity Extension. Since this is fairly trivial, you could easily do it with a regular old Extension method, which would result in less setup code. </p>
<p>Basically the extension going to do is drill into the impl type and extract the interface that matches the passed in generic, and register it in the container. </p>
<h5>The Unity Extension</h5>
<div>
<div class="csharpcode">
<pre class="alt"><span class="kwrd">public</span> <span class="kwrd">class</span> OpenGenericExtension : UnityContainerExtension, IOpenGenericExtension</pre>
<pre class="alteven">{</pre>
<pre class="alt">    <span class="kwrd">protected</span> <span class="kwrd">override</span> <span class="kwrd">void</span> Initialize()</pre>
<pre class="alteven">    {</pre>
<pre class="alt">       </pre>
<pre class="alteven">    }</pre>
<pre class="alt">&#160;</pre>
<pre class="alteven">    <span class="kwrd">public</span> <span class="kwrd">void</span> RegisterClosedImpl&lt;T&gt;(Type openGenericInterface)</pre>
<pre class="alt">    {</pre>
<pre class="alteven">        var closedType = <span class="kwrd">typeof</span>(T);</pre>
<pre class="alt">&#160;</pre>
<pre class="alteven">        closedType.GetInterfaces()</pre>
<pre class="alt">                  .Where(x =&gt; x.IsGenericType)</pre>
<pre class="alteven">                  .Where(x =&gt; x.GetGenericTypeDefinition() == openGenericInterface)</pre>
<pre class="alt">                  .ToList()</pre>
<pre class="alteven">                  .ForEach(x =&gt; Container.RegisterType(x, closedType));</pre>
<pre class="alt">    }</pre>
<pre class="alteven">}</pre>
</p></div>
</div>
<div>
<div class="csharpcode">
<pre class="alt"><span class="kwrd">public</span> <span class="kwrd">interface</span> IOpenGenericExtension : IUnityContainerExtensionConfigurator</pre>
<pre class="alteven">{</pre>
<pre class="alt">    <span class="kwrd">void</span> RegisterClosedImpl&lt;T&gt;(Type openInterface);</pre>
<pre class="alteven">}</pre>
</p></div>
</div>
<div>&#160;</div>
<h4>The Test</h4>
<p>Make it go.</p>
<div>
<div class="csharpcode">
<pre class="alt">[Test]</pre>
<pre class="alteven"><span class="kwrd">public</span> <span class="kwrd">void</span> should_connect_types()</pre>
<pre class="alt">{</pre>
<pre class="alteven">    var container = <span class="kwrd">new</span> UnityContainer();</pre>
<pre class="alt">    container.AddNewExtension&lt;OpenGenericExtension&gt;()</pre>
<pre class="alteven">             .Configure&lt;IOpenGenericExtension&gt;()</pre>
<pre class="alt">             .RegisterClosedImpl&lt;OrderCanceledEvent&gt;(<span class="kwrd">typeof</span>(IHandler&lt;&gt;));</pre>
<pre class="alteven">&#160;</pre>
<pre class="alt">    var handler = container.Resolve&lt;IHandler&lt;OrderCanceledMessage&gt;&gt;();</pre>
<pre class="alteven">&#160;</pre>
<pre class="alt">    Assert.AreEqual(handler.GetType(), <span class="kwrd">typeof</span>(OrderCanceledEvent));</pre>
<pre class="alteven">}</pre>
</p></div>
</div>
]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/12/18/advanced-unity-connecting-implementations-to-open-generic-types/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Unity Extension for Entity Framework POCO Configuration, Repository and Unit of Work</title>
		<link>http://elegantcode.com/2009/12/15/building-a-unity-extension-for-entity-framework-poco-configuration-repository-and-unit-of-work/</link>
		<comments>http://elegantcode.com/2009/12/15/building-a-unity-extension-for-entity-framework-poco-configuration-repository-and-unit-of-work/#comments</comments>
		<pubDate>Wed, 16 Dec 2009 00:35:20 +0000</pubDate>
		<dc:creator>Jarod Ferguson</dc:creator>
				<category><![CDATA[Entity Framework]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/12/15/building-a-unity-extension-for-entity-framework-poco-configuration-repository-and-unit-of-work/</guid>
		<description><![CDATA[In my previous two posts I talk about simple EF4 mappings and some common abstractions I like to work with for my entity persistence operations. In this post I want to take all of the setup code necessary for EF configuration and registration and encapsulate it along with the standard boiler plate IOC container code [...]]]></description>
			<content:encoded><![CDATA[<p>In my previous two posts I talk about <a href="http://elegantcode.com/2009/12/15/entity-framework-poco-ef4-a-simple-mapping/">simple EF4 mappings</a> and some <a href="http://elegantcode.com/2009/12/15/entity-framework-ef4-generic-repository-and-unit-of-work-prototype/">common abstractions</a> I like to work with for my entity persistence operations. In this post I want to take all of the setup code necessary for EF configuration and registration and encapsulate it along with the standard boiler plate IOC container code you might see in an application BootStrapper.</p>
<p>&#160;</p>
<h4>A Typical DI Example</h4>
<p>Though its pretty typical, I thought it would be good to show an example of how I expect to work with a Repository in my application. The “End Result” if you will.</p>
<p>The following is how one of my MVC.NET controllers might look (same for domain services, WCF services etc). Dependencies are satisfied via constructor injection when the controller or service is built up by the infrastructure (ControllerFactory or perhaps WCF IInstanceProvider).</p>
<div>
<div class="csharpcode">
<pre class="alt"><span class="kwrd">public</span> <span class="kwrd">class</span> RosterController</pre>
<pre class="alteven">{</pre>
<pre class="alt">   <span class="kwrd">private</span> <span class="kwrd">readonly</span> IRepository&lt;Team&gt; _teamRepository;</pre>
<pre class="alteven">&#160;</pre>
<pre class="alt">   <span class="kwrd">public</span> RosterController(IRepository&lt;Team&gt; teamRepository)</pre>
<pre class="alteven">   {</pre>
<pre class="alt">       _teamRepository = teamRepository;</pre>
<pre class="alteven">   }</pre>
<pre class="alt">&#160;</pre>
<pre class="alteven">   <span class="kwrd">public</span> <span class="kwrd">void</span> AddNewPlayer(<span class="kwrd">long</span> teamId, <span class="kwrd">string</span> playerName, <span class="kwrd">string</span> position)</pre>
<pre class="alt">   {</pre>
<pre class="alteven">       var team = _teamRepository.First(x =&gt; x.ID == teamId);</pre>
<pre class="alt">       team.Players.Add(<span class="kwrd">new</span> Player{ Name = playerName, Position = position });</pre>
<pre class="alteven">   }</pre>
<pre class="alt">}</pre>
</p></div>
</div>
<p>In order to “wire up” the above example, there is quite a bit that has to happen. </p>
<p>&#160;</p>
<h4></h4>
<h4>The Unity Extension</h4>
<p>Unity provides extension points, called UnityContainerExtension’s which are a perfect place to handle IOC initialization for a given component. For those familiar with Castle Windsor facilities, its kind of like that (or StructureMap registries). </p>
<p>The EFRepositoryExtension (could probably use a better name?) handles:</p>
<ul>
<li>Creating the ContextBuilder and registering it with the Container </li>
<li>Registering the Generic Repository&lt;T&gt; and UnitOfWork </li>
<li>Context Lifetime </li>
<li>Entity Configuration &amp; EntitySet Registration </li>
<li>Context BuildUp </li>
</ul>
<p>The end result is nice clean extension I can register in my BootStrapper like so:</p>
<div>
<div class="csharpcode">
<pre class="alt">var container = IoC.Container; <span class="rem">//some static, thread safe container class</span></pre>
<pre class="alteven">&#160;</pre>
<pre class="alt">container.AddNewExtension&lt;EFRepositoryExtension&gt;();</pre>
<pre class="alteven">container.Configure&lt;IEFRepositoryExtension&gt;()</pre>
<pre class="alt">         .WithConnection(cnxString)</pre>
<pre class="alteven">         .WithContextLifetime(<span class="kwrd">new</span> HttpContextLifetimeManager&lt;IObjectContext&gt;())</pre>
<pre class="alt">         .ConfigureEntity(<span class="kwrd">new</span> TeamConfiguration())</pre>
<pre class="alteven">         .ConfigureEntity(<span class="kwrd">new</span> PlayerConfiguration());</pre>
</p></div>
</div>
<div>A pretty nice API to work with if I get to say so <img src='http://elegantcode.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </div>
<div>&#160;</div>
<h5>Fluent Interface</h5>
<div>
<div class="csharpcode">
<pre class="alt"><span class="kwrd">public</span> <span class="kwrd">interface</span> IEFRepositoryExtension : IUnityContainerExtensionConfigurator</pre>
<pre class="alteven">{</pre>
<pre class="alt">    IEFRepositoryExtension WithConnection(<span class="kwrd">string</span> connectionString);</pre>
<pre class="alteven">    IEFRepositoryExtension WithContextLifetime(LifetimeManager lifetimeManager);</pre>
<pre class="alt">    IEFRepositoryExtension ConfigureEntity&lt;T&gt;(EntityConfiguration&lt;T&gt; config);</pre>
<pre class="alteven">    IEFRepositoryExtension ConfigureEntity&lt;T&gt;(EntityConfiguration&lt;T&gt; config, <span class="kwrd">string</span> setName);</pre>
<pre class="alt">}</pre>
</p></div>
</div>
<h5>Extension Implementation</h5>
<div>
<div class="csharpcode">
<pre class="alt"><span class="kwrd">public</span> <span class="kwrd">class</span> EFRepositoryExtension : UnityContainerExtension, IEFRepositoryExtension</pre>
<pre class="alteven">{</pre>
<pre class="alt">  <span class="kwrd">private</span> ContextBuilder&lt;ObjectContext&gt; _builder;</pre>
<pre class="alteven">  <span class="kwrd">private</span> SqlConnection _connection;</pre>
<pre class="alt">&#160;</pre>
<pre class="alteven">  <span class="kwrd">protected</span> <span class="kwrd">override</span> <span class="kwrd">void</span> Initialize()</pre>
<pre class="alt">  {</pre>
<pre class="alteven">      _builder = <span class="kwrd">new</span> ContextBuilder&lt;ObjectContext&gt;();</pre>
<pre class="alt">      <span class="rem">//register the builder instance as a singleton, this will hold all of our </span></pre>
<pre class="alteven">      <span class="rem">//mapping information for the duration of our application as it creates </span></pre>
<pre class="alt">      <span class="rem">//new data contexts</span></pre>
<pre class="alteven">      Container.RegisterInstance(<span class="str">&quot;builder&quot;</span>, _builder, </pre>
<pre class="alt">                                 <span class="kwrd">new</span> ContainerControlledLifetimeManager());</pre>
<pre class="alteven">&#160;</pre>
<pre class="alt">      <span class="rem">//Register Repo &amp; UOW. Those these are transient instances, they both take</span></pre>
<pre class="alteven">      <span class="rem">//a ctor dependency on the ObjectContext which has its lifetime controlled</span></pre>
<pre class="alt">      <span class="rem">//by the Extension. E.g., for an Http current request, all repository and</span></pre>
<pre class="alteven">      <span class="rem">//UOW will use the same context/transaction</span></pre>
<pre class="alt">      Container.RegisterType(<span class="kwrd">typeof</span>(IRepository&lt;&gt;), <span class="kwrd">typeof</span>(Repository&lt;&gt;));</pre>
<pre class="alteven">      Container.RegisterType&lt;IUnitOfWork, UnitOfWork&gt;();</pre>
<pre class="alt">  }</pre>
<pre class="alteven">&#160;</pre>
<pre class="alt">  <span class="kwrd">public</span> IEFRepositoryExtension WithConnection(<span class="kwrd">string</span> connectionString)</pre>
<pre class="alteven">  {</pre>
<pre class="alt">      _connection = <span class="kwrd">new</span> SqlConnection(connectionString);</pre>
<pre class="alteven">      <span class="kwrd">return</span> <span class="kwrd">this</span>;</pre>
<pre class="alt">  }</pre>
<pre class="alteven">&#160;</pre>
<pre class="alt">  <span class="kwrd">public</span> IEFRepositoryExtension ConfigureEntity&lt;T&gt;(EntityConfiguration&lt;T&gt; config)</pre>
<pre class="alteven">  {</pre>
<pre class="alt">      <span class="rem">//simple pluralization of the entity set</span></pre>
<pre class="alteven">      ConfigureEntity(config, <span class="kwrd">typeof</span>(T).Name+<span class="str">&quot;s&quot;</span>);</pre>
<pre class="alt">      <span class="kwrd">return</span> <span class="kwrd">this</span>;</pre>
<pre class="alteven">  }</pre>
<pre class="alt">&#160;</pre>
<pre class="alteven">  <span class="kwrd">public</span> IEFRepositoryExtension ConfigureEntity&lt;T&gt;(EntityConfiguration&lt;T&gt; config, </pre>
<pre class="alt">                                                   <span class="kwrd">string</span> setName)</pre>
<pre class="alteven">  {</pre>
<pre class="alt">      <span class="rem">//add the configuration</span></pre>
<pre class="alteven">      _builder.Configurations.Add(config);</pre>
<pre class="alt">      <span class="rem">//register the set metadata</span></pre>
<pre class="alteven">      _builder.RegisterSet&lt;T&gt;(setName);</pre>
<pre class="alt">      <span class="kwrd">return</span> <span class="kwrd">this</span>;</pre>
<pre class="alteven">  }</pre>
<pre class="alt">&#160;</pre>
<pre class="alteven">  <span class="kwrd">public</span> IEFRepositoryExtension WithContextLifetime(LifetimeManager lifetimeManager)</pre>
<pre class="alt">  {</pre>
<pre class="alteven">      Container.AddNewExtension&lt;StaticFactoryExtension&gt;();</pre>
<pre class="alt">      Container.Configure&lt;IStaticFactoryConfiguration&gt;()</pre>
<pre class="alteven">               .RegisterFactory&lt;IObjectContext&gt;(x =&gt; </pre>
<pre class="alt">                   ContextResolver(x, lifetimeManager, _connection));</pre>
<pre class="alteven">      </pre>
<pre class="alt">      <span class="kwrd">return</span> <span class="kwrd">this</span>;</pre>
<pre class="alteven">  }</pre>
<pre class="alt">&#160;</pre>
<pre class="alteven">  <span class="rem">//factory func to build context with given lifetime &amp; connection</span></pre>
<pre class="alt">  <span class="kwrd">static</span> <span class="kwrd">readonly</span> Func&lt;IUnityContainer, LifetimeManager, SqlConnection, <span class="kwrd">object</span>&gt; </pre>
<pre class="alteven">      ContextResolver = (c, l, s) =&gt;</pre>
<pre class="alt">      {</pre>
<pre class="alteven">          var context = l.GetValue();</pre>
<pre class="alt">          <span class="kwrd">if</span> (context == <span class="kwrd">null</span>)</pre>
<pre class="alteven">          {</pre>
<pre class="alt">              var builder = c.Resolve&lt;ContextBuilder&lt;ObjectContext&gt;&gt;(<span class="str">&quot;builder&quot;</span>);</pre>
<pre class="alteven">              var newContext = builder.Create(s);</pre>
<pre class="alt">              context = <span class="kwrd">new</span> ObjectContextAdapter(newContext);</pre>
<pre class="alteven">              l.SetValue(context);</pre>
<pre class="alt">          }</pre>
<pre class="alteven">&#160;</pre>
<pre class="alt">          <span class="kwrd">return</span> context;</pre>
<pre class="alteven">      };</pre>
<pre class="alt">}</pre>
</p></div>
</div>
<p>&#160;</p>
<h4>The Test</h4>
<p>Doing simple service location &amp; using TestLifetime, my prototype (not really a “test” I suppose)looks like:</p>
<div>
<div class="csharpcode">
<pre class="alt">var cnxString = ConfigurationManager.ConnectionStrings[<span class="str">&quot;Test&quot;</span>].ConnectionString;</pre>
<pre class="alteven">var container = IoC.Container; <span class="rem">//some static, thread safe container class</span></pre>
<pre class="alt">&#160;</pre>
<pre class="alteven">container.AddNewExtension&lt;EFRepositoryExtension&gt;();</pre>
<pre class="alt">container.Configure&lt;IEFRepositoryExtension&gt;()</pre>
<pre class="alteven">&#160;&#160;&#160; .WithConnection(cnxString)</pre>
<pre class="alt">&#160;&#160;&#160; .WithContextLifetime(<span class="kwrd">new</span> TestLifetimeManager&lt;IObjectContext&gt;())</pre>
<pre class="alteven">&#160;&#160;&#160; .ConfigureEntity(<span class="kwrd">new</span> TeamConfiguration())</pre>
<pre class="alt">&#160;&#160;&#160; .ConfigureEntity(<span class="kwrd">new</span> PlayerConfiguration());</pre>
<pre class="alteven">&#160;</pre>
<pre class="alt">container.RegisterType&lt;RosterController&gt;();</pre>
<pre class="alteven">&#160;</pre>
<pre class="alt">var rosterController = container.Resolve&lt;RosterController&gt;();</pre>
<pre class="alteven">&#160;</pre>
<pre class="alt">rosterController.AddNewPlayer(3, <span class="str">&quot;Austin Collie&quot;</span>, <span class="str">&quot;&quot;</span>);</pre>
<pre class="alteven">&#160;</pre>
<pre class="alt">container.Resolve&lt;IUnitOfWork&gt;().Commit();</pre>
</p></div>
</div>
<p>&#160;</p>
<p>Thoughts and feedback are welcome.</p>
]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/12/15/building-a-unity-extension-for-entity-framework-poco-configuration-repository-and-unit-of-work/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Entity Framework POCO (EF4): Generic Repository and Unit of Work Prototype</title>
		<link>http://elegantcode.com/2009/12/15/entity-framework-ef4-generic-repository-and-unit-of-work-prototype/</link>
		<comments>http://elegantcode.com/2009/12/15/entity-framework-ef4-generic-repository-and-unit-of-work-prototype/#comments</comments>
		<pubDate>Tue, 15 Dec 2009 19:53:02 +0000</pubDate>
		<dc:creator>Jarod Ferguson</dc:creator>
				<category><![CDATA[Entity Framework]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/12/15/entity-framework-ef4-generic-repository-and-unit-of-work-prototype/</guid>
		<description><![CDATA[In my previous post I demonstrated how to create a simple mapping using the latest EF4 CTP. In this post I will look at how I can customize some infrastructure code in an attempt to align EF POCO “Code Only” with existing patterns, while potentially increasing reuse and testability.
A popular pattern for ORM data access [...]]]></description>
			<content:encoded><![CDATA[<p>In my <a href="http://elegantcode.com/2009/12/15/entity-framework-poco-ef4-a-simple-mapping/">previous post</a> I demonstrated how to create a simple mapping using the latest EF4 CTP. In this post I will look at how I can customize some infrastructure code in an attempt to align EF POCO “Code Only” with existing patterns, while potentially increasing reuse and testability.</p>
<p>A popular pattern for ORM data access is the Repository pattern. Implementing a generic repository in EF4 gets much easier with ObjectSet&lt;T&gt;. One might argue that it is, in a sense, a Repository. </p>
<p>What I would like to do is “Adapt” this interface to my own generic Repository. This will let me customize the interface to my own specifications and remove the dependency in my domain services on ObjectSet&lt;T&gt;. </p>
<p>Here is a <a href="http://devtalk.dk/CommentView,guid,b5d9cad2-e155-423b-b66f-7ec287c5cb06.aspx">great article</a> based on the last CTP that does a nice job of laying out a Repository&lt;T&gt; strategy with a UnitOfWork, and here is <a href="http://blogs.hibernatingrhinos.com/nhibernate/archive/0001/01/01/the-repository-pattern.aspx">another</a> using nHibernate (see also <a href="http://blogs.hibernatingrhinos.com/nhibernate/archive/2008/04/10/nhibernate-and-the-unit-of-work-pattern.aspx">UnitOfWork</a> examples). If you are not familiar with the Generic Repository pattern and UnitOfWork, you should take a quick second and skim these before you continue. I want to take this implementation and try and change just a few things about it. </p>
<ul>
<li><strong>Static Unit of Work reference</strong>: First, I want to remove the Repository static reference to the UnitOfWork, which is how the Repository in the examples are resolving the ObjectContext/Session. Aside from not being a fan of static classes, I think it is the application Container’s responsibility to manage dependency resolution. Plus, I don&#8217;t really know that I want my Repository to have <em>any </em>reference to the UnitOfWork. I want the UnitOfWork to span across multiple repositories within a given transaction. </li>
<li><strong>Object Lifetime</strong>: I would like to have more granular control over the UnitOfWork and ObjectContext lifetime. In the authors example, the UnitOfWork is managing the lifetime strategy, which is something the Container is perfect at handling. I will leave the UOW to transaction management only. </li>
<li><strong>Constructor Injection</strong>: I think since the Repository has a hard dependency on the ObjectContext, that it would make the most sense to have the ObjectContext injected into Repository ctor. </li>
<li><strong>Concrete ObjectContext reference</strong>: Since I will now be passing the ObjectContext into the ctor, I feel better if this was an interface. Not that I foresee a tremendous amount of testable value here, but I still don&#8217;t like taking a ctor dependency on a framework object if I can avoid it. Plus, this is prototype code, so why not? </li>
</ul>
<h4>Repository Interface</h4>
<p>You will notice the interface remains unchanged from the first referenced article <em>(Update: changed Func&lt;T, bool&gt; to Expression&lt;Func&lt;T, bool&gt;&gt; so that expressions can be evaluated correctly by ObjectQuery)</em></p>
<div>
<div class="csharpcode">
<pre class="alt"><span class="kwrd">public</span> <span class="kwrd">interface</span> IRepository&lt;T&gt; <span class="kwrd">where</span> T : <span class="kwrd">class</span></pre>
<pre class="alteven">{</pre>
<pre class="alt">    IQueryable&lt;T&gt; AsQueryable();</pre>
<pre class="alteven">&#160;</pre>
<pre class="alt">    IEnumerable&lt;T&gt; GetAll();</pre>
<pre class="alteven">    IEnumerable&lt;T&gt; Find(Expression&lt;Func&lt;T, <span class="kwrd">bool</span>&gt;&gt; <span class="kwrd">where</span>);</pre>
<pre class="alt">    T Single(Expression&lt;Func&lt;T, <span class="kwrd">bool</span>&gt;&gt; <span class="kwrd">where</span>);</pre>
<pre class="alteven">    T First(Expression&lt;Func&lt;T, <span class="kwrd">bool</span>&gt;&gt; <span class="kwrd">where</span>);</pre>
<pre class="alt">&#160;</pre>
<pre class="alteven">    <span class="kwrd">void</span> Delete(T entity);</pre>
<pre class="alt">    <span class="kwrd">void</span> Add(T entity);</pre>
<pre class="alteven">    <span class="kwrd">void</span> Attach(T entity);</pre>
<p>}</p></div>
</div>
<p>&#160;</p>
<h4>Generic Repository Implementation</h4>
<p>As I described in the bullets above, my implementation does in fact take the IObjectContext as a ctor argument. Also, notice that I do not have any static references.</p>
<div>
<div class="csharpcode">
<pre class="alt"><span class="kwrd">public</span> <span class="kwrd">class</span> Repository&lt;T&gt; : IRepository&lt;T&gt; <span class="kwrd">where</span> T : <span class="kwrd">class</span></pre>
<pre class="alteven">{</pre>
<pre class="alt">   IObjectSet&lt;T&gt; _objectSet;</pre>
<pre class="alteven">&#160;</pre>
<pre class="alt">   <span class="kwrd">public</span> Repository(IObjectContext objectContext)</pre>
<pre class="alteven">   {</pre>
<pre class="alt">       _objectSet = objectContext.CreateObjectSet&lt;T&gt;();</pre>
<pre class="alteven">   }</pre>
<pre class="alt">&#160;</pre>
<pre class="alteven">   <span class="kwrd">public</span> IQueryable&lt;T&gt; AsQueryable()</pre>
<pre class="alt">   {</pre>
<pre class="alteven">       <span class="kwrd">return</span> _objectSet;</pre>
<pre class="alt">   }</pre>
<pre class="alteven">&#160;</pre>
<pre class="alt">   <span class="kwrd">public</span> IEnumerable&lt;T&gt; GetAll()</pre>
<pre class="alteven">   {</pre>
<pre class="alt">       <span class="kwrd">return</span> _objectSet.ToList();</pre>
<pre class="alteven">   }</pre>
<pre class="alt">&#160;</pre>
<pre class="alteven">   <span class="kwrd">public</span> IEnumerable&lt;T&gt; Find(Expression&lt;Func&lt;T, <span class="kwrd">bool</span>&gt;&gt; <span class="kwrd">where</span>)</pre>
<pre class="alt">   {</pre>
<pre class="alteven">       <span class="kwrd">return</span> _objectSet.Where(<span class="kwrd">where</span>);</pre>
<pre class="alt">   }</pre>
<pre class="alteven">&#160;</pre>
<pre class="alt">   <span class="kwrd">public</span> T Single(Expression&lt;Func&lt;T, <span class="kwrd">bool</span>&gt;&gt; <span class="kwrd">where</span>)</pre>
<pre class="alteven">   {</pre>
<pre class="alt">       <span class="kwrd">return</span> _objectSet.Single(<span class="kwrd">where</span>);</pre>
<pre class="alteven">   }</pre>
<pre class="alt">&#160;</pre>
<pre class="alteven">   <span class="kwrd">public</span> T First(Expression&lt;Func&lt;T, <span class="kwrd">bool</span>&gt;&gt; <span class="kwrd">where</span>)</pre>
<pre class="alt">   {</pre>
<pre class="alteven">       <span class="kwrd">return</span> _objectSet.First(<span class="kwrd">where</span>);</pre>
<pre class="alt">   }</pre>
<pre class="alteven">&#160;</pre>
<pre class="alt">   <span class="kwrd">public</span> <span class="kwrd">void</span> Delete(T entity)</pre>
<pre class="alteven">   {</pre>
<pre class="alt">       _objectSet.DeleteObject(entity);</pre>
<pre class="alteven">   }</pre>
<pre class="alt">&#160;</pre>
<pre class="alteven">   <span class="kwrd">public</span> <span class="kwrd">void</span> Add(T entity)</pre>
<pre class="alt">   {</pre>
<pre class="alteven">       _objectSet.AddObject(entity);</pre>
<pre class="alt">   }</pre>
<pre class="alteven">&#160;</pre>
<pre class="alt">   <span class="kwrd">public</span> <span class="kwrd">void</span> Attach(T entity)</pre>
<pre class="alteven">   {</pre>
<pre class="alt">       _objectSet.Attach(entity);</pre>
<pre class="alteven">   }</pre>
<p>}</p></div>
</div>
<p>&#160;</p>
<h4>Unit of Work</h4>
<p>Just like EF4 ObjectSet does a lot out of box for our Repository, the EF ObjectContext really does a lot of the work for us in regards to managing the UnitOfWork. The Object context is already capable of handling a transaction across many operations over different types. So, again, we are going to just add a little wrapper around the context and call it a UnitOfWork. This will give me a nice hook where my infrastructure can snag a reference to the ObjectContext and Commit the transaction changes, for example, at the end of a WCF, Web or DataService request.</p>
<div>
<div class="csharpcode">
<pre class="alt"><span class="kwrd">interface</span> IUnitOfWork</pre>
<pre class="alteven">{</pre>
<pre class="alt">    <span class="kwrd">void</span> Commit();</pre>
<pre class="alteven">}</pre>
<pre class="alt">&#160;</pre>
<pre class="alteven"><span class="kwrd">public</span> <span class="kwrd">class</span> UnitOfWork: IUnitOfWork, IDisposable</pre>
<pre class="alt">{</pre>
<pre class="alteven">    <span class="kwrd">private</span> <span class="kwrd">readonly</span> IObjectContext _objectContext;</pre>
<pre class="alt">&#160;</pre>
<pre class="alteven">    <span class="kwrd">public</span> UnitOfWork(IObjectContext objectContext)</pre>
<pre class="alt">    {</pre>
<pre class="alteven">        _objectContext = objectContext;</pre>
<pre class="alt">    }</pre>
<pre class="alteven">&#160;</pre>
<pre class="alt">    <span class="kwrd">public</span> <span class="kwrd">void</span> Dispose()</pre>
<pre class="alteven">    {</pre>
<pre class="alt">        <span class="kwrd">if</span> (_objectContext != <span class="kwrd">null</span>)</pre>
<pre class="alteven">        {</pre>
<pre class="alt">            _objectContext.Dispose();</pre>
<pre class="alteven">        }</pre>
<pre class="alt">        GC.SuppressFinalize(<span class="kwrd">this</span>);</pre>
<pre class="alteven">    }</pre>
<pre class="alt">&#160;</pre>
<pre class="alteven">    <span class="kwrd">public</span> <span class="kwrd">void</span> Commit()</pre>
<pre class="alt">    {</pre>
<pre class="alteven">        _objectContext.SaveChanges();</pre>
<pre class="alt">    }</pre>
<pre class="alteven">}</pre>
</p></div>
</div>
<h4>&#160;</h4>
<h4>The Object Context Adapter</h4>
<p>Just some Adapter 101 code here to abstract away the Concrete Context</p>
<div>
<div class="csharpcode">
<pre class="alt"><span class="kwrd">public</span> <span class="kwrd">interface</span> IObjectContext : IDisposable</pre>
<pre class="alteven">{</pre>
<pre class="alt">    IObjectSet&lt;T&gt; CreateObjectSet&lt;T&gt;() <span class="kwrd">where</span> T : <span class="kwrd">class</span>;</pre>
<pre class="alteven">    <span class="kwrd">void</span> SaveChanges();</pre>
<pre class="alt">}</pre>
<pre class="alteven">&#160;</pre>
<pre class="alt"><span class="kwrd">public</span> <span class="kwrd">class</span> ObjectContextAdapter : IObjectContext</pre>
<pre class="alteven">{</pre>
<pre class="alt">    <span class="kwrd">readonly</span> ObjectContext _context;</pre>
<pre class="alteven">&#160;</pre>
<pre class="alt">    <span class="kwrd">public</span> ObjectContextAdapter(ObjectContext context)</pre>
<pre class="alteven">    {</pre>
<pre class="alt">        _context = context;</pre>
<pre class="alteven">    }</pre>
<pre class="alt">&#160;</pre>
<pre class="alteven">    <span class="kwrd">public</span> <span class="kwrd">void</span> Dispose()</pre>
<pre class="alt">    {</pre>
<pre class="alteven">        _context.Dispose();</pre>
<pre class="alt">    }</pre>
<pre class="alteven">&#160;</pre>
<pre class="alt">    <span class="kwrd">public</span> IObjectSet&lt;T&gt; CreateObjectSet&lt;T&gt;() <span class="kwrd">where</span> T : <span class="kwrd">class</span></pre>
<pre class="alteven">    {</pre>
<pre class="alt">        <span class="kwrd">return</span> _context.CreateObjectSet&lt;T&gt;();</pre>
<pre class="alteven">    }</pre>
<pre class="alt">&#160;</pre>
<pre class="alteven">    <span class="kwrd">public</span> <span class="kwrd">void</span> SaveChanges()</pre>
<pre class="alt">    {</pre>
<pre class="alteven">        _context.SaveChanges();</pre>
<pre class="alt">    }</pre>
<pre class="alteven">}</pre>
</p></div>
</div>
<h4>&#160;</h4>
<h4>Using the Repository</h4>
<p>Without out my application Container, here is how I would code up the new abstractions:</p>
<div>
<div>
<div class="csharpcode">
<pre class="alt"><span class="rem">//...</span></pre>
<pre class="alteven"><span class="rem">// a bunch of ugly set up code here, see previous post</span></pre>
<pre class="alt"><span class="rem">//...</span></pre>
<pre class="alteven">&#160;</pre>
<pre class="alt">var context = builder.Create(connection);</pre>
<pre class="alteven">var contextAdapter = <span class="kwrd">new</span> ObjectContextAdapter(context);</pre>
<pre class="alt">var unitOfWork = <span class="kwrd">new</span> UnitOfWork(contextAdapter);</pre>
<pre class="alteven">&#160;</pre>
<pre class="alt">var teamRepository = <span class="kwrd">new</span> Repository&lt;Team&gt;(contextAdapter);</pre>
<pre class="alteven">var newTeam = <span class="kwrd">new</span> Team { Name = <span class="str">&quot;Da Bears&quot;</span> };</pre>
<pre class="alt">&#160;</pre>
<pre class="alteven">teamRepository.Add(newTeam);</pre>
<pre class="alt">unitOfWork.Commit();</pre>
<pre class="alteven">&#160;</pre>
<pre class="alt">var team = teamRepository.First(x =&gt; x.Name == <span class="str">&quot;Da Bears&quot;</span>);</pre>
<pre class="alteven">Console.WriteLine(team.Name);</pre>
<pre class="alt">&#160;</pre>
<pre class="alteven">context.Dispose();</pre>
</p></div>
</p></div>
</div>
<p><strong></strong></p>
<p><strong>Admittedly, this is not very pretty and is still way more than I want to deal with on regular basis. </strong>In my next post I will demonstrate how I will tie all this together, <a href="http://elegantcode.com/2009/12/15/building-a-unity-extension-for-entity-framework-poco-configuration-repository-and-unit-of-work/">EF Configuration, Repository and UnitOfWork using a Unity Extension</a>. </p>
<p>Please keep in mind this is prototype, untested code on a CTP release. Code at your own risk!</p>
]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/12/15/entity-framework-ef4-generic-repository-and-unit-of-work-prototype/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
		<item>
		<title>Entity Framework POCO (EF4): A Simple Mapping</title>
		<link>http://elegantcode.com/2009/12/15/entity-framework-poco-ef4-a-simple-mapping/</link>
		<comments>http://elegantcode.com/2009/12/15/entity-framework-poco-ef4-a-simple-mapping/#comments</comments>
		<pubDate>Tue, 15 Dec 2009 06:47:12 +0000</pubDate>
		<dc:creator>Jarod Ferguson</dc:creator>
				<category><![CDATA[Entity Framework]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/12/15/entity-framework-poco-ef4-a-simple-mapping/</guid>
		<description><![CDATA[The latest EF4 CTP released on November 12th includes updated support for POCO’s (Plain Ol’ CLR Objects). Although we could use POCO’s in the previous CTP, we still had to create an EDMX artifact to model our entities, thus leading to a bit of duplication. 
In this post I want to take a look a [...]]]></description>
			<content:encoded><![CDATA[<p>The <a href="http://blogs.msdn.com/adonet/archive/2009/11/12/updated-feature-ctp-walkthrough-code-only-for-entity-framework.aspx">latest EF4 CTP</a> released on November 12th includes updated support for POCO’s (Plain Ol’ CLR Objects). Although we could use POCO’s in the previous CTP, we still had to create an EDMX artifact to model our entities, thus leading to a bit of duplication. </p>
<p>In this post I want to take a look a simple mapping scenario, and how that looks using the new ‘Code Only’ API. By using the code only API I can have complete control over my entities, giving me the most flexibility in my mapping strategies, better testability and extensibility, and ultimately greater maintainability. No generated code. No XML files. Sweet <img src='http://elegantcode.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<p>Since I am a sports fanatic I am going to use one of my favorite models, the sports team. (Hey, I could be using Orders!)</p>
<h5></h5>
<h4>The Database Table</h4>
<p>I will start by defining a simple table with 2 columns, Name and ID:</p>
<div>
<div class="csharpcode">
<pre class="alt">CREATE TABLE [dbo].[Teams](</pre>
<pre class="alteven">    [ID] [bigint] IDENTITY(1,1) NOT NULL,</pre>
<pre class="alt">    [Name] [nvarchar](50) NULL,</pre>
<pre class="alteven"> CONSTRAINT [PK_Team] PRIMARY KEY CLUSTERED ([Id] ASC)</pre>
<pre class="alt">) ON [PRIMARY]</pre>
<pre class="alteven">&#160;</pre>
<pre class="alt">GO</pre>
</p></div>
</div>
<p>&#160;</p>
<h4>The Entity</h4>
<p>When creating an Entity the default convention is that the Entity property names should match the database column names exactly. I will create a <strong>Team</strong> entity which does that like so:</p>
<div>
<div style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px">
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #0000ff">public</span> <span style="color: #0000ff">class</span> Team</pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px">{</pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px">    <span style="color: #0000ff">public</span> <span style="color: #0000ff">long</span> Id { get; set; }</pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px">    <span style="color: #0000ff">public</span> <span style="color: #0000ff">string</span> Name { get; set; }</pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px">}</pre>
</p></div>
</div>
</p>
</p>
<h4>The Mapping</h4>
<p>Mapping the Entity to the table is very easy. To do so, implement a Generic class EntityConfiguration&lt;T&gt; and setup the map in the ctor. For the <strong>Team</strong> entity, that will look like this:</p>
<div>
<div style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px">
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #0000ff">public</span> <span style="color: #0000ff">class</span> TeamConfiguration : EntityConfiguration&lt;Team&gt;</pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px">{</pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px">    <span style="color: #0000ff">public</span> TeamConfiguration()</pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px">    {</pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px">        Property(c =&gt; c.Id).IsIdentity();</pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px">        Property(c =&gt; c.Name).HasMaxLength(50).IsRequired();</pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px">    }</pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px">}</pre>
</p></div>
<p>The EntityConfiguration methods contain many overloads which provide a variety of mapping options. For now, I will leave it simple.</p></div>
<p>&#160;</p>
<h4>The Infrastructure</h4>
<p>Now that I have the entity and table mapped together, I need to provide the EF infrastructure with the configuration, and then I can begin working with the Entity(ies).</p>
<h5>Connection</h5>
<p>A simple connection string. I felt this was worth pointing out for those that have used EF3.5. Note that this is just a simple DB connection, and does not contain the metadata parts.</p>
<div>
<div style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px">
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px">&lt;configuration&gt;</pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px">  &lt;connectionStrings&gt;</pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px">    &lt;add name=<span style="color: #006080">&quot;Test&quot;</span> connectionString=<span style="color: #006080">&quot;Data Source=.;Initial Catalog=Test;</pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px">        Integrated Security=True;MultipleActiveResultSets=True&quot;</span>/&gt;</pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px">  &lt;/connectionStrings&gt;</pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px">&lt;/configuration&gt;</pre>
</p></div>
</div>
<p>&#160;</p>
<h5>The Object Context</h5>
<p>If you look at the <a href="http://blogs.msdn.com/adonet/pages/feature-ctp-walkthrough-code-only-for-the-entity-framework.aspx">CTP walkthrough</a> you will notice the sample includes a class called BloggingModel which derives from ObjectContext. BloggingModel has properties for each ObjectSet&lt;T&gt;. I believe this is done so that the ContextBuilder can infer the EntitySets and build the correct metadata. To me this is an unnecessary class that I would rather not maintain. Instead, before I create the context,&#160; I will handle the metadata registration by calling “builder.RegisterSet&lt;T&gt;(&quot;SetName&quot;);” <em>(For now… see future post).</em>&#160; If I did not do this, the context would use the default naming convention for our EntitySet, and would expect a table named “TeamSet”.</p>
<div>
<div class="csharpcode">
<pre class="alt"><span class="rem">//create builder</span></pre>
<pre class="alteven">var builder = <span class="kwrd">new</span> ContextBuilder&lt;ObjectContext&gt;();</pre>
<pre class="alt">&#160;</pre>
<pre class="alteven"><span class="rem">//add our Team set configuration</span></pre>
<pre class="alt">builder.Configurations.Add(<span class="kwrd">new</span> TeamConfiguration());</pre>
<pre class="alteven"><span class="rem">//keep in mind this call is to avoid custom object context</span></pre>
<pre class="alt">builder.RegisterSet&lt;Team&gt;(<span class="str">&quot;Teams&quot;</span>);</pre>
<pre class="alteven">&#160;</pre>
<pre class="alt"><span class="rem">//setup connection</span></pre>
<pre class="alteven">var cnxString = ConfigurationManager.ConnectionStrings[<span class="str">&quot;Test&quot;</span>].ConnectionString;</pre>
<pre class="alt">var connection = <span class="kwrd">new</span> SqlConnection(cnxString);</pre>
<pre class="alteven">&#160;</pre>
<pre class="alt"><span class="rem">//create the context</span></pre>
<pre class="alteven">var context = builder.Create(connection);</pre>
<pre class="alt">&#160;</pre>
<pre class="alteven"><span class="rem">//now we have a good context, and can go to work</span></pre>
<pre class="alt">var teams = context.CreateObjectSet&lt;Team&gt;();</pre>
<pre class="alteven">teams.AddObject(<span class="kwrd">new</span> Team { Name = <span class="str">&quot;New Orleans Saints&quot;</span> });</pre>
<pre class="alt">context.SaveChanges();</pre>
<pre class="alteven">context.Dispose();</pre>
</p></div>
</div>
<p>Aside from some of the context setup code, it’s fairly straight forward. Simple data access with a POCO entity.&#160; check.</p>
<p>&#160;</p>
<h4>Extending the Entity with a One-to-Many Relationship</h4>
<p>Now that I have the basic mapping down, I want to go one step further and add a one-to-many relationship. What’s a team without players? </p>
<h5></h5>
<h5>Player Table</h5>
<div>
<div class="csharpcode">
<pre class="alt">CREATE TABLE [dbo].[Players](</pre>
<pre class="alteven">    [ID] [bigint] IDENTITY(1,1) NOT NULL,</pre>
<pre class="alt">    [Team_ID] [bigint] NOT NULL,</pre>
<pre class="alteven">    [Name] [nvarchar](50) NOT NULL,</pre>
<pre class="alt">    [Position] [nvarchar](50) NOT NULL,</pre>
<pre class="alteven"> CONSTRAINT [PK_Players] PRIMARY KEY CLUSTERED ([ID] ASC)</pre>
<pre class="alt">) </pre>
<pre class="alteven">&#160;</pre>
<pre class="alt">GO</pre>
<pre class="alteven">&#160;</pre>
<pre class="alt">ALTER TABLE [dbo].[Players]  WITH CHECK ADD  CONSTRAINT [FK_Players_Teams] FOREIGN KEY([Team_ID])</pre>
<pre class="alteven">REFERENCES [dbo].[Teams] ([ID])</pre>
<pre class="alt">GO</pre>
<pre class="alteven">&#160;</pre>
<pre class="alt">ALTER TABLE [dbo].[Players] CHECK CONSTRAINT [FK_Players_Teams]</pre>
<pre class="alteven">GO</pre>
</p></div>
</div>
<h5>Entities and Mappings</h5>
<p>I have added an ICollection to <strong>Team</strong> for the Players, and each <strong>Player</strong> has a 1-1 <strong>Team </strong>property. Mapping the collection is straight forward by using the “Relationship()”&#160; method which takes my expression for the properties I am mapping too.</p>
<div>
<div class="csharpcode">
<pre class="alt"><span class="kwrd">public</span> <span class="kwrd">class</span> Team</pre>
<pre class="alteven">{</pre>
<pre class="alt">    <span class="kwrd">public</span> Team()</pre>
<pre class="alteven">    {</pre>
<pre class="alt">        Players = <span class="kwrd">new</span> Collection&lt;Player&gt;();</pre>
<pre class="alteven">    }</pre>
<pre class="alt">    <span class="kwrd">public</span> <span class="kwrd">long</span> ID { get; set; }</pre>
<pre class="alteven">    <span class="kwrd">public</span> <span class="kwrd">string</span> Name { get; set; }</pre>
<pre class="alt">    <span class="kwrd">public</span> ICollection&lt;Player&gt; Players { get; set; }</pre>
<pre class="alteven">}</pre>
<pre class="alt">&#160;</pre>
<pre class="alteven"><span class="kwrd">public</span> <span class="kwrd">class</span> Player</pre>
<pre class="alt">{</pre>
<pre class="alteven">    <span class="kwrd">public</span> <span class="kwrd">long</span> ID { get; set; }</pre>
<pre class="alt">    <span class="kwrd">public</span> <span class="kwrd">string</span> Name { get; set; }</pre>
<pre class="alteven">    <span class="kwrd">public</span> <span class="kwrd">string</span> Position { get; set; }</pre>
<pre class="alt">    <span class="kwrd">public</span> Team Team { get; set; }</pre>
<pre class="alteven">}</pre>
<pre class="alt">&#160;</pre>
<pre class="alteven"><span class="kwrd">public</span> <span class="kwrd">class</span> TeamConfiguration : EntityConfiguration&lt;Team&gt;</pre>
<pre class="alt">{</pre>
<pre class="alteven">    <span class="kwrd">public</span> TeamConfiguration()</pre>
<pre class="alt">    {</pre>
<pre class="alteven">        Property(c =&gt; c.ID).IsIdentity();</pre>
<pre class="alt">        Property(c =&gt; c.Name).HasMaxLength(50).IsRequired();</pre>
<pre class="alteven">        <span class="rem">// 1 to * relationships     </span></pre>
<pre class="alt">        Relationship(c =&gt; c.Players).IsOptional();</pre>
<pre class="alteven">        <span class="rem">//set up inverse</span></pre>
<pre class="alt">        Relationship(c =&gt; c.Players).FromProperty(x =&gt; x.Team);</pre>
<pre class="alteven">    }</pre>
<pre class="alt">}</pre>
<pre class="alteven">&#160;</pre>
<pre class="alt"><span class="kwrd">public</span> <span class="kwrd">class</span> PlayerConfiguration : EntityConfiguration&lt;Player&gt;</pre>
<pre class="alteven">{</pre>
<pre class="alt">    <span class="kwrd">public</span> PlayerConfiguration()</pre>
<pre class="alteven">    {</pre>
<pre class="alt">        Property(c =&gt; c.ID).IsIdentity();</pre>
<pre class="alteven">        Property(c =&gt; c.Name).HasMaxLength(50).IsRequired();</pre>
<pre class="alt">        Property(c =&gt; c.Position).HasMaxLength(50).IsRequired();</pre>
<pre class="alteven">               </pre>
<pre class="alt">        Relationship(c =&gt; c.Team).IsRequired();</pre>
<pre class="alteven">        Relationship(c =&gt; c.Team).FromProperty(x =&gt; x.Players); </pre>
<pre class="alt">    }</pre>
<pre class="alteven">}</pre>
</p></div>
</div>
<div>&#160;</div>
<div>Now that the relationship is defined, I can work just as I would with a simple collection:</div>
<div>&#160;</div>
<div>
<div class="csharpcode">
<pre class="alt">var teams = context.CreateObjectSet&lt;Team&gt;();</pre>
<pre class="alteven">var team = <span class="kwrd">new</span> Team { Name = <span class="str">&quot;Indianapolis Colts&quot;</span> };</pre>
<pre class="alt">var player1 = <span class="kwrd">new</span> Player { Name = <span class="str">&quot;Peyton Manning&quot;</span>, Position = <span class="str">&quot;QB&quot;</span>};</pre>
<pre class="alteven">var player2 = <span class="kwrd">new</span> Player { Name = <span class="str">&quot;Reggie Wayne&quot;</span>, Position = <span class="str">&quot;WR&quot;</span> };</pre>
<pre class="alt">&#160;</pre>
<pre class="alteven">team.Players.Add(player1);</pre>
<pre class="alt">team.Players.Add(player2);</pre>
<pre class="alteven">&#160;</pre>
<pre class="alt">teams.AddObject(team);</pre>
<pre class="alteven">context.SaveChanges();</pre>
<pre class="alt">&#160;</pre>
<pre class="alteven"><span class="rem">//create new player set to show we are pulling back from db</span></pre>
<pre class="alt">var players = context.CreateObjectSet&lt;Player&gt;().Include(<span class="str">&quot;Team&quot;</span>)</pre>
<pre class="alteven">                    .Where(x =&gt; x.Team.Name == <span class="str">&quot;Indianapolis Colts&quot;</span>)</pre>
<pre class="alt">                    .ToList();</pre>
<pre class="alteven">players.ForEach(x =&gt; Console.WriteLine(x .Name + <span class="str">&quot; - &quot;</span> + x.Team.Name));</pre>
<pre class="alt">&#160;</pre>
<pre class="alteven">context.Dispose();</pre>
</p></div>
</div>
<div>&#160;</div>
<p>And that’s it. </p>
<p>While I was working on this sample I bumped into quite a few common scenarios which are not yet supported. Seeing how this is an early CTP, I suppose that is to be expected. That said, I am excited to see the direction it is taking and look forward to learning more as I have time to work with it.</p>
<p>For more information take a look at the <a href="http://blogs.msdn.com/adonet/archive/tags/Entity+Framework+Feature+CTP2+for+.NET+4.0/default.aspx">related EF posts</a> on the ADO.NET team blog.</p>
]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/12/15/entity-framework-poco-ef4-a-simple-mapping/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
		</item>
		<item>
		<title>IIS 7.5 &#8211; 401.3 Unauthorized when trying to read a javascript file</title>
		<link>http://elegantcode.com/2009/11/23/iis-7-5-401-3-unauthorized-when-trying-to-read-a-javascript-file/</link>
		<comments>http://elegantcode.com/2009/11/23/iis-7-5-401-3-unauthorized-when-trying-to-read-a-javascript-file/#comments</comments>
		<pubDate>Mon, 23 Nov 2009 06:32:52 +0000</pubDate>
		<dc:creator>Jarod Ferguson</dc:creator>
				<category><![CDATA[Esoterica]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/11/23/iis-7-5-401-3-unauthorized-when-trying-to-read-a-javascript-file/</guid>
		<description><![CDATA[Here is one that took me entirely too long to figure out. I downloaded this Nifty Corners Cube javascript… plugin I guess Ill call it? It was used in a past project I was on and I thought it was pretty cool. It will definitely save some time putting out a decent UX without having [...]]]></description>
			<content:encoded><![CDATA[<p>Here is one that took me entirely too long to figure out. I downloaded this <a href="http://www.html.it/articoli/niftycube/index.html">Nifty Corners Cube</a> javascript… plugin I guess Ill call it? It was used in a past project I was on and I thought it was pretty cool. It will definitely save some time putting out a decent UX without having to round a bunch of images. </p>
<p>Anyway, I download the new version and for the life of me could not figure out why the fetch the blasted thing kept giving me 401’s. You know, the type of scenario when you strip out all asp.net security, grant ‘everyone’ full control of the entire website file system and run SysInternals procmon. Ya one of those.</p>
<p>So here was the deal: (right click js –&gt; properties –&gt; advanced)</p>
<p>&#160;</p>
<p><a href="http://elegantcode.com/wp-content/uploads/2009/11/image8.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://elegantcode.com/wp-content/uploads/2009/11/image_thumb8.png" width="367" height="282" /></a> </p>
<p>&#160;</p>
<p>I don&#8217;t know how or why that box gets checked, but if it is, then IIS will not read the file. Period.</p>
<p>So don’t check it <img src='http://elegantcode.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/11/23/iis-7-5-401-3-unauthorized-when-trying-to-read-a-javascript-file/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Why I didn&#8217;t blog from March-August (off topic&#8230; a little)</title>
		<link>http://elegantcode.com/2009/11/23/why-i-didnt-blog-from-march-august-off-topic-a-little/</link>
		<comments>http://elegantcode.com/2009/11/23/why-i-didnt-blog-from-march-august-off-topic-a-little/#comments</comments>
		<pubDate>Mon, 23 Nov 2009 06:04:18 +0000</pubDate>
		<dc:creator>Jarod Ferguson</dc:creator>
				<category><![CDATA[Esoterica]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/11/23/why-i-didnt-blog-from-march-august-off-topic-a-little/</guid>
		<description><![CDATA[Some of you who follow Elegant Code, as well as some of the Elegant Coders may have wondered why my blog went dark for a while this last year.
Well, sometimes life just kicks you in the balls.
Lets rewind to January of 2009. My wife Katy and I own 3 properties, one we live in, one [...]]]></description>
			<content:encoded><![CDATA[<p>Some of you who follow Elegant Code, as well as some of the Elegant Coders may have wondered why my blog went dark for a while this last year.</p>
<p>Well, sometimes life just kicks you in the balls.</p>
<p>Lets rewind to January of 2009. My wife Katy and I own 3 properties, one we live in, one was on the market for sale (wife&#8217;s old condo), and one was being rented. (all of them upside down, go economy! woo!)</p>
<p>On January 25th we found the one that was vacant flooded! The line that was connected to the icemaker had broken off the fridge and had been running for 3 weeks. It ruined the house, nearly 40k worth of damage. Luckily insurance covered the repairs, but what a timesuck mess, and we are still fixing things today (we live there now).</p>
<p>If that isn’t bad enough, we get a call in late February from the police that the tenants in our rental house have been arrested for drugs! After evicting them and viewing the property, we were in shock. The house was completely thrashed! Full of trash, holes in walls &amp; doors, urine soaked carpets, counter tops burnt and chipped. Since this was strike 2,&#160; PARK PLACE PROPERTY MANAGEMENT IN BOISE IDAHO WAS SO FIRED! </p>
<p>The house needed renovating, and we couldn&#8217;t afford to hire someone. So we did it ourselves. Katy made this cool slideshow, so I thought I would share it with you.</p>
<p>&#160;</p>
<p><embed height="325" width="550" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" name="rockyou" wmode="transparent" salign="lt" scale="noscale" quality="high" src="http://apps.rockyou.com/rockyou.swf?instanceid=155072379&amp;ver=102906" /></embed></p>
<p>&#160;</p>
<p>Here is what we did (more or less)</p>
<ul>
<li>Ripped out carpet, treated sub-floor for odor</li>
<li>Replaces 3 doors, including front door (door installer, I salute you!)</li>
<li>Tiled countertops</li>
<li>Spray all cabinets and trim</li>
<li>Paint entire interior, including ceiling &amp; doors</li>
<li>Re-grout shower/bathtub tile</li>
<li>Replace all interior light fixtures</li>
<li>Replace bathroom vanity</li>
<li>Replace fridge main board &amp; shelving</li>
<li>Install new sink &amp; faucet</li>
<li>Install new dishwasher </li>
<li>Install new oven/range</li>
<li>All new carpet &amp; vinyl installed</li>
<li>Have driveway poured on side of house to meet parking reqs (city violated us)&#160; </li>
<li>Have new fence in backyard installed for privacy</li>
<li>Had some electrical brought to code</li>
<li>Installed new smoke detector system</li>
</ul>
<ul>Probably some more stuff, but you get the idea, a complete flip.</ul>
<ul>The house came out amazing and is currently rented by a small family who really likes the place. All of this cost us about 12k, and nearly 6 mos of every weekend and 2-3 weeknights per week. (I took off a weekend for Boise code camp!)</ul>
<p>It really was a test of all tests. Katy and I look back and still cant believe we did it, 2 engineers at that. Most people I think would have quit, given the house(es) back to the bank. We are not most people <img src='http://elegantcode.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>… and for the encore, I quit my day job and started my own company.</p>
]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/11/23/why-i-didnt-blog-from-march-august-off-topic-a-little/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>DTO&#8217;s, DDD &amp; The Anemic Domain Model</title>
		<link>http://elegantcode.com/2009/11/13/dtos-ddd-the-anemic-domain-model/</link>
		<comments>http://elegantcode.com/2009/11/13/dtos-ddd-the-anemic-domain-model/#comments</comments>
		<pubDate>Sat, 14 Nov 2009 00:17:43 +0000</pubDate>
		<dc:creator>Jarod Ferguson</dc:creator>
				<category><![CDATA[Esoterica]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/11/13/dtos-ddd-the-anemic-domain-model/</guid>
		<description><![CDATA[I had a comment on my last post Tips for ORM Data Access which i would like like to address with this blog post.
I have been trying to wrap my head around the role of the DTO in DDD. My reading of Fowler and Evans seems to indicate that you ought to have your domain [...]]]></description>
			<content:encoded><![CDATA[<p>I had a comment on my last post <a href="http://elegantcode.com/2009/11/12/tips-for-orm-data-access/comment-page-1/#comment-50298">Tips for ORM Data Access</a> which i would like like to address with this blog post.</p>
<blockquote><p><em>I have been trying to wrap my head around the role of the DTO in DDD. My reading of Fowler and Evans seems to indicate that you ought to have your domain objects themselves mapping into your database, rather than dedicated function-less DTOs. Relying on DTOs that are then handled by Services seems to lead to what Fowler calls The Anemic Domain Anti-Pattern: </em><a href="http://martinfowler.com/bliki/AnemicDomainModel.html"><em>http://martinfowler.com/bliki/AnemicDomainModel.html</em></a></p>
<p><em>However, I have a tough time writing Entity classes that operate in that manner that don’t end up rather painful to change and extend.</em></p>
<p><em>Since you recommend the practice of using DTOs, do you have any thoughts on the subject?</em></p>
</blockquote>
<p>Thank you for the question Scott, of course I have thoughts on this <img src='http://elegantcode.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p><strong><em>Disclaimer: This sort of architecture is not applicable to many systems, use the right patterns and tools for the job! </em></strong></p>
<p>I agree that an anemic domain model is bad, if there is no behavior then what’s the point right? Let’s make sure I am on the same page here: </p>
<p>DTO: To me, a DTO moves data between ‘tiers’. They are the packaged data ready for transport. A WCF data contract is a perfect example of a DTO, I also see a JSON object as a DTO. </p>
<p>Read model: This would be a different model than your real Domain model.&#160; A Read model is very lightweight, ‘thin’ and anemic.&#160; Its purpose is to serve aggregated data to a specific screen or message. A DTO, to me, can be a read model, as too could be a View Model. </p>
<p>The domain model is rich and full of behavior. This model is most valuable when performing complex business rules during the saving and updating of data within a given transaction. It can also be used to read data too, but consider this contrived example: </p>
<p>Let’s say that we want to display the top 10 products. The products include the Manufacturer Name, Product Name, Vendor Name,&#160; Product Price,&#160; Customer Ranking. Being that we are good modelers we come up with something like the following entities: Vendor, Manufacturer, Product,&#160; &amp;&#160; ProductRanking (maybe localization &amp; currency support tables too).</p>
<p>If I use my domain model to get this data, I am going to end up retrieving quite a bit more data than I actually need, which could degrade performance. Not to mention having to deal with dot notation everywhere foo.Name =a.b.c.d.&#160; </p>
<p>We only need 5 fields, and they are immutable for this operation. </p>
<p>My preference is to materialize the read model (DTO, View Model) by projecting from the Domain Model, or by using a Stored Procedure for more complicated recursive, spatial or temporal queries. </p>
<p>Splitting the models allows the reads &amp; writes to fluctuate independently, so which leads to higher maintainability. These models can also run on different tiers/nodes to increase scalability (read/cache tier, write tier). </p>
<p>At some point, whether off a view or an inbound DTO, there will be mapping back into the domain model. This ‘friction’ or ‘impedance’ is pretty easy to manage using an assembler/translator, or a tool like AutoMapper. </p>
<p>Greg Young &amp; Udi Dahan take this concept further and apply a programming principle called Command-Query Separation with distributed programming and SOA. I think it is very good stuff. </p>
<p>Here are some posts that are all somewhat related:   <br /><a href="http://jonathan-oliver.blogspot.com/2009/03/dddd-and-cqs-getting-started.html">http://jonathan-oliver.blogspot.com/2009/03/dddd-and-cqs-getting-started.html</a>    <br /><a href="http://www.udidahan.com/2008/08/11/command-query-separation-and-soa/">http://www.udidahan.com/2008/08/11/command-query-separation-and-soa/</a>    <br /><a href="http://codebetter.com/blogs/gregyoung/archive/2009/08/13/command-query-separation.aspx">http://codebetter.com/blogs/gregyoung/archive/2009/08/13/command-query-separation.aspx</a>    <br /><a href="http://elegantcode.com/2008/04/27/dtos-or-serialized-domain-entities/">http://elegantcode.com/2008/04/27/dtos-or-serialized-domain-entities/</a>    <br /><a href="http://elegantcode.com/2008/04/30/altnet-seattle-takeawayddddresources/">http://elegantcode.com/2008/04/30/altnet-seattle-takeawayddddresources/</a></p>
]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/11/13/dtos-ddd-the-anemic-domain-model/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Tips for ORM Data Access</title>
		<link>http://elegantcode.com/2009/11/12/tips-for-orm-data-access/</link>
		<comments>http://elegantcode.com/2009/11/12/tips-for-orm-data-access/#comments</comments>
		<pubDate>Thu, 12 Nov 2009 22:32:24 +0000</pubDate>
		<dc:creator>Jarod Ferguson</dc:creator>
				<category><![CDATA[Esoterica]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/11/12/tips-for-orm-data-access/</guid>
		<description><![CDATA[In my last post I took a stab at Lazy Loading data access, and pointed out a concrete example of why I don’t like it. As with anything there are trade-offs. Here are a few practices I use for clean and fast data access. They are heavily influenced by some common patterns from PoEAA, and [...]]]></description>
			<content:encoded><![CDATA[<p>In my <a href="http://elegantcode.com/2009/11/12/lazy-loading-is-well-lazy/">last post I took a stab at Lazy Loading data access</a>, and pointed out a concrete example of why I don’t like it. As with anything there are trade-offs. Here are a few practices I use for clean and fast data access. They are heavily influenced by some common patterns from <a href="http://www.amazon.com/Patterns-Enterprise-Application-Architecture-Martin/dp/0321127420">PoEAA</a>, and <a href="http://www.amazon.com/Domain-Driven-Design-Tackling-Complexity-Software/dp/0321125215/ref=sr_1_1?ie=UTF8&amp;s=books&amp;qid=1258062865&amp;sr=1-1">Domain Driven Design</a>. </p>
<ul>
<li>Retrieve data by <a href="http://www.lostechies.com/blogs/jimmy_bogard/archive/2008/05/20/entities-value-objects-aggregates-and-roots.aspx">aggregate roots</a>, have a <a href="http://martinfowler.com/eaaCatalog/repository.html">repository</a> for each root. The root queries should return the entire aggregate. If you are going to defer loading to a part of the root graph, be explicit. Instead of lazy loading Foo.Bars, I like to say Foo.LoadBars() &lt;- yes seriously</li>
<li>Learn how to <a href="http://www.udidahan.com/2009/01/24/ddd-many-to-many-object-relational-mapping/">identify the right aggregate</a> </li>
<li>Respect your aggregate root boundaries. Aggregates cannot call into other aggregates children! You shouldn’t be adding a product from the order, really, this is bad: LineItem.Product.Calatalog.Add(new Product). The order AR just crossed into the Catalog AR. Its not the job of the Order to add products to the catalog</li>
<li>Do not try an overuse an aggregate, its ok to create a new one. Less is more does not apply. Fulfilling an order is different than placing one, and your data access may need to reflect that</li>
<li>Use a ‘Read Model’. The most common approach here is using <a href="http://martinfowler.com/eaaCatalog/dataTransferObject.html">DTO</a> or <a href="http://geekswithblogs.net/michelotti/archive/2009/10/25/asp.net-mvc-view-model-patterns.aspx">ViewModel</a>, and <a href="http://cetinbasoz.spaces.live.com/Blog/cns!D13F81744709AB9F!209.entry?sa=914843388">projecting</a> straight into it from the object model query or database </li>
<li>For complex queries that perform aggregations and calculations, consider using a store procedure. They really have their place, even with the best ORM’s (then project into Read Model)</li>
<li>Avoid putting query logic in mappings (<a href="http://martinfowler.com/eaaCatalog/dataTransferObject.html">Assembler’s</a>, Translators, <a href="http://www.codeplex.com/AutoMapper">AutoMapper</a>) </li>
<li>Use a tracing tool. I like the <a href="http://www.developer.com/db/article.php/3482216/Introduction-to-SQL-Profiler.htm">SQL trace profiler</a>, but if you are not as comfortable with sql, there is a some good profilers around, like <a href="http://www.nhprof.com/">NHProf</a> for nHiberante &amp; soon <a href="http://ayende.com/Blog/archive/2009/11/06/entity-framework-profiler.aspx">EFProf</a> for the Entity Framework </li>
<li>Know the SQL that is going to your database. Have your <a href="http://blogs.microsoft.co.il/blogs/gilf/archive/2009/02/06/totracestring-method-in-entity-framework.aspx">tests emit the generated sql out to the console</a>. Live it, learn it, love it. You should know your ORM tendencies, especially if you are using a linq provider </li>
<li>Batch requests to your <a href="http://davybrion.com/blog/2008/06/batching-wcf-calls/">services</a> and <a href="http://davybrion.com/blog/2009/04/transparent-query-batching-through-your-repository/">database</a>, especially if you are in a web or distributed environment</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/11/12/tips-for-orm-data-access/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>Lazy Loading is&#8230; well&#8230; lazy</title>
		<link>http://elegantcode.com/2009/11/12/lazy-loading-is-well-lazy/</link>
		<comments>http://elegantcode.com/2009/11/12/lazy-loading-is-well-lazy/#comments</comments>
		<pubDate>Thu, 12 Nov 2009 22:31:13 +0000</pubDate>
		<dc:creator>Jarod Ferguson</dc:creator>
				<category><![CDATA[Esoterica]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/11/12/lazy-loading-is-well-lazy/</guid>
		<description><![CDATA[I find it ironic that we allow our tooling to mask the biggest bottleneck in the system: The database. Having worked with the majority of the ORM tools out there, I can tell you the most common contributor to slow system performance is lazy loading for Data Access. 
I’ve seen this one all too many [...]]]></description>
			<content:encoded><![CDATA[<p><strong>I find it ironic that we allow our tooling to mask the biggest bottleneck in the system: The database.</strong> Having worked with the majority of the ORM tools out there, I can tell you <strong>the most common contributor to slow system performance is <a href="http://en.wikipedia.org/wiki/Lazy_loading">lazy loading</a> for Data Access.</strong> </p>
<p>I’ve seen this one all too many times:</p>
<blockquote><p><strong>Business guy:</strong> The order checkout screen is running slow in production</p>
<p><strong>Dev:</strong> It shouldn’t be, it runs great on my machine</p>
<p><strong>Business guy:</strong> Well, it is. It takes 10-15 seconds to load order 123</p>
<p><strong>Dev:</strong> Let me check, ya hmm, it is slow. I’ll look into it</p>
</blockquote>
<p>The developer proceeds to crack open the source where he finds some <a href="http://en.wikipedia.org/wiki/Law_of_Demeter">LOD</a> nightmare data binding mess in the view, or the mapping to the <a href="http://martinfowler.com/eaaDev/PresentationModel.html">presentation model</a>: “Customer.Order-&gt; LineItem.Product.Catalog.Vendor.Name”</p>
<p>Because someone wanted to display the Vendor name on the line detail, they just hopped over the graph and loaded the catalog, and then vendor. So here comes the entire catalog! (of course its <a href="http://ayende.com/Blog/archive/2006/05/02/CombatingTheSelectN1ProblemInNHibernate.aspx">N + 1</a>) </p>
<p><strong>Why did they do that? Because it is EASY</strong>! (and because your boss wanted it yesterday)</p>
<p>The team never knows about it until it’s too late. Yep, it runs fast locally, because we developers only have a small catalog on our machine, I mean “we don’t want all that data on our box”.</p>
<p>Now I know there are many folks out there saying “Well that’s just stupid, I would never do that”. Maybe you wouldn’t, but that guy sitting next to you, he will. I tell you, we all do it, again and again.</p>
<p><strong>The result over time is an interconnected web of queries that can bring a system to a crawl</strong>.</p>
<p><a href="http://elegantcode.com/2009/11/12/tips-for-orm-data-access/">See my follow up post</a> for some tips I use when designing a data access layer with an ORM</p>
]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/11/12/lazy-loading-is-well-lazy/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
	</channel>
</rss>
