Injection Dependency

Published 11/20/2008 by Adam Wolf in c# | Development | Patterns | Principles
Tags: , ,

On January 22, 2009, I will be giving a presentation at the Southeast Valley .Net Users Group on Building Flexible Applications with a Dependency Injection Container. The presentation will cover the common uses of a dependency injection container and show how they can help create applications that are more testable, maintainable and resilient to change. The presentation will also cover some common development principles like SRP, LSP, OCP and ISP.

Scheduled Demonstrations:

  • Using Castle Windsor and the MVP pattern in an Asp.Net website
  • Creating an extensible and configurable pipeline processor using Ninject
  • Decorator chains and aspect oriented programming using Unity from Microsoft

It’s the new year and hopefully you have made a New Year’s resolution to get involved with the community. So, come out, have some pizza, and learn something new. My company Blue Cognition LLC is sponsoring the presentation, so don't worry about pushy recruiters.


In my next blog on the SEVDNUG ORM shootout series, I am going to show how the LINQ to SQL ORM can be used with a Domain Driven Design (DDD) philosophy. To give people a better understanding of DDD, I decided to group all of my DDD books into this one review. Domain Driven Design is more of a philosophy than a technique or a methodology. It is in this philosophy or understanding that complexity in a computer system is broken down into a model that contains the systems business logic.

Over the last decade or two, a philosophy has developed as an undercurrent in the object community. The premise of Domain-Driven Design is two-fold:
  • For most software projects, the primary focus should be on the domain and domain logic.
  • Complex domain designs should be based on a model.
From: www.domaindrivendesign.org

I have used the DDD techniques found in the books in this review to build systems with some very good success, and that success was dependent on the frequent open communication with the domain experts. If you cannot get a client or organization to agree on open communication with domain experts, then using DDD would be inappropriate and I would look for other, more traditional, techniques like waterfall.


 

Domain Driven Design Tackling Complexity in the Heart of Software

Title: Domain Driven Design
Auther: Eric Evans
Publisher: Addison Wesley
ISBN: 0321125215
Copyright: 2004
Rating: Excellent

If Domain Driven Design were a religion then this would be “The Good Book”. In “Domain-Driven Design Tackling Complexity in the Heart of Software” Eric Evans has distilled his object modeling and development philosophy insight into a readable and readily usable book. I really enjoyed this book and I have read sections of the book many times gaining more insight into the object domain-modeling world each time. If you are going to purchase one book on DDD, then this is the one you should purchase.


 

Applying Domain Driven Design and Patterns with Examples in C#

Title: Applying Domain Driven Design and Patterns
Auther: Jimmy Nilsson
Publisher: Addison Wesley
ISBN: 0321268202
Copyright: 2006
Rating: Great

Jimmy Nilsson has expertly combined Domain Driven Design, Enterprise Application Architecture, Test Driven Development and the C# language into a single approachable text for the .Net Developer. In the book, you will find real world examples that shows how DDD and enterprise architecture combine to develop working and, more importantly, maintainable software. Jimmy has done a tremendous job on “Appling Domain Driven Design and Patterns with Examples in C#.” If you know C#, this book will teach you how to use DDD with enterprise architecture and how to do it correctly.


 

.Net Domain Driven Design with C#

Title: .Net Domain Driven Design with C#
Auther: Tim McCarthy
Publisher: Wrox
ISBN: 9780470147566
Copyright: 2008
Rating: Good

When learning a topic as big as Domain Driven Design (DDD), an example is very helpful and that is what Tim McCarthy has provided in “.Net Domain Driven Design with C#.” The community surrounding the DDD movements has been asking for a more thorough example application using the Domain Driven Design technique. Tim starts from the bottom and in successive chapters builds a DDD inspired application complete with all the major DDD concepts covered. If you need an example application to help you learn DDD, then this book is what you are looking for.

I need to warn readers that this book has a terrible binding and it's printed on toilet paper. I suggest you do not highlight pages in this book because they will bleed through multiple pages. Wrox should upgrade the paper from toilet paper to something above tissue paper!


During a tech lunch ("A meeting of geeks over a burrito") I was telling my colleagues about an inversion of control (IOC) and dependency injection (DI) container that I was using on my latest project and they wanted to know how I decide on using the SpringFramework.Net (Spring). My response was that I chose the Spring framework because it was ported from Java (“as are many good things”) and was backed by a company that was supporting the open source efforts. I also told them that it was mainly because of the awesome documentation the Spring framework has in place.

Most of the IOC and DI framework like Spring, Castle Windsor, Structure Map, have communities of people to help with problems you might have but for me nothing beats solving my own problems with the documentation in hand. Each of these projects has some form of startups and help documents but Spring has a wealth of current and approachable documentation in many different formats. My favorite is the PDF documentation because I can sit down at night and read it on my slate pc like I am reading a good book. Yes, I am a geek!

Some people and organizations pick frameworks and methodology because of the company behind them. Microsoft is the company that comes to mind first, but this is not the best way to truly evaluate whether it will be the best fit for your project or organization. Choosing a framework should not be a trivial task and should be entered into like a marriage, you wouldn’t get married after the second date, would you? Once committed to a framework, you should try to use the framework in a way that you could easily swap it out and use another framework if a problem arises.

One of the main benefits of open source projects is in its open licensing and its inherent flexibility to change. If a selected framework does not have a feature you need for your project, you can request it from the project developers, develop it yourself and have it added to the framework or you can branch the source and add it yourself. This type of change would be hard for company frameworks to achieve but Microsoft is starting to build its current frameworks like ASP.Net MVC and Unity with easy extensibility points as a first class feature.

List of Containers

  • SpringFramework.Net
  • Castle Windsor
  • Structure Map
  • Microsoft Unity

Conclusion

The advise I give clients is to research your preferred framework and find out how easy it will be to get support or help when you have a problem. If the community and the development is active and current, then you have a good indication that the framework will have a good lifetime. With an active community, help will be available during and after your project has been deployed.


Have you ever wished that Microsoft added a ForEach() method to the IEnumerable Interface? Well now you don’t have to wish, all you have to do is fire up the IDE and hook up some extension methods that will give you the functionality you are looking for. Now you might be thinking ‘hey does this guy know about GetEnumerator()?’ and the answer is yes; but wouldn't you like to write in your code something like the snippet below.

PersonEnumerable.ForEach( c => Console.WriteLine(“Hello my name is {0}.”,c.Name));

I know its only snytatic sugar, but it is sweet. Extension methods are not the answer for many problems but it can help you solve a few.

What are Extension Methods?

Extension methods allow you to add methods to the public contract of any type without changing or sub-classing the original type, somewhat like C++ non member functions. These “Duck-Typed” methods are static but are called just like instance methods on the applied type. To use an extension method and to have it applied to the target type you must add a using statement in your code to the namespace that holds the extension method static class that implements the extension method. For instance, if you extended string in your AppExtension namespace you will need to add a using statement to the AppExtension namespace in every class where you want to use the new method on the string type.

Are Extension Methods Evil?

One of the main concerns for developers using extension methods is in the way your extension method can be silently overridden by a method with the same signature on the target type. The C# compiler and Visual Studio will not warn you about changes in your code when an extension method has been replaced by a method on the target type. The results of this silent shift from extension method to type method will probably have unintended consequences in your code. This shifting is more likely when you change from one version of a library to another, like when upgrading an application to a newer version of the .Net framework. 

Sample

using System.Collections.Generic;
 
namespace BlueCognition.Infrastructure
{
    public interface IVisitor<T>
    {
        void Visit(T item);
    }
}
 
namespace BlueCognition.Infrastructure.Extentions
{
    public static class EnumerableExtensionGateway
    {
        public static void Visit<T>(this IEnumerable<T> items, 
            BlueCognition.Infrastructure.IVisitor<T> visitor)
        {
            new EnumerableActions<T>(items).Visit(visitor);
        }
    }
    
    public class EnumerableActions<T>
    {
        private IEnumerable<T> itemsToVisit;
 
        public EnumerableActions(IEnumerable<T> listToVisit)
        {
            this.itemsToVisit = listToVisit;
        }
 
        public void Visit(IVisitor<T> visitor)
        {
            foreach (T t in itemsToVisit)
            {
                visitor.Visit(t);
            }
        }
    }
}

Guidelines

I originally had this section named Extension Methods Best Practices but I think the name was premature. I will revisit this blog post and update it when I have further insight into the better practices concerning extension methods.

  • Quarantine your extension methods: Do not put your extension methods into the System namespace or other namespaces used by Microsoft. Quarantine your extension methods into specific namespaces, so that if you want to use them in your code you must import the namespace. This will effectively reduce the scope of your extension specific to the task at hand.
  • Use your own types: Use your own types when possible in the method signature of your extension methods. For example, if you want to create a “Visit” extension method on IEnumerable, I would create an IVisitor interface and pass a type that implemented that interface to the extension method instead of using the Action<t> type because this would effectively shield you from a possible future addition of a Visit(Action<T>) on the IEnumerable interface from Microsoft.
  • Make them testable: Make extension methods easily testable by delegating the work in the static extension method to another type. This will enable you to test the functionality of the extension in isolation without having to directly deal with the extended type.
  • No string libraries: Creating string extension methods libraries for validation is not a good idea and should be avoided. An extension method like IsValidEmailAddress() added to String would be a code smell to me and I would remove the extension and create a value type for EmailAddress and then add the validation to that type.

Conclusion

I would suggest using the new extension method functionality in .Net 3.0 sparingly, and only use it if there are no other good alternatives. The standard OOP practices of inheritance for extending types that you own makes more sense to me than extending it with extension methods. The use of extension methods attached to interfaces will make a very powerful addition to every type that implements that interface. My first extension is going to be extending the IEnumerable class with a ForEach(Action<t>) or maybe a Visit(IVisitor visitor) method like shown in this post.

Links


Be Specific of T

Published 2/12/2007 by Adam Wolf in Development | Patterns
Tags: ,

Every application has business rules and constraints that need to apply to its domain model. The rules can be simple like validating a new invoice that has today’s date or complex like checking a customer’s credit line before an order can be processed. These rules should be implemented in a consistent and maintainable fashion in the domain model with the ability to combine rules together to make more complex rules. A specification is a design pattern or development guideline on how to implement and use these rule objects.

Specification states a constraint on the state of another object, which may or may not be present. It has multiple uses, but one that conveys the most basic concept is that a specification can test any object to see if it satisfies the specified criteria. Domain Driven Design By Erric Evans

Specifications And Their Uses

  1. Object Validation: The specification should be usable to validate a single object. This is usually accomplished by a method on the specification called IsSatisfiedBy().
  2. Select From Collection: Selecting from a collection with the use of a specification is easier then specifying the criteria in a long list of method parameters. You would normally see methods on entity repositories that will take a specification and return a collection of matching entities.
  3. Specify the Criteria of a New Object: The specification in conjunction with the factory pattern can make creating objects easier.

ISpecification & IExpressionSpecification  

When implementing the specification pattern normally, you will have a single method that takes an object and will return you a boolean value that determines if the object has met the criteria expressed in the specification. The IExpressionSpecification of T inherits from ISpecification<T> so that it can be used just like a normal ISpecification<T>.

    public interface ISpecification<T>
    {
        bool IsSatisfiedBy(T target);
    }
 
    public interface IExpressionSpecification<T> : ISpecification<T>
    {
        Expression<Func<T, bool>> Predicate { get; }
        IExpressionSpecification<T> And(IExpressionSpecification<T> other);
        IExpressionSpecification<T> Or(IExpressionSpecification<T> other);
    }

ExpressionSpecification Abstract Class

Using the expression data structure from the Linq namespaces makes this specification pattern easier to implement for the first and second uses of the specifications pattern. The method IsSatisfiedBy() uses the expression data structure by compiling it into a TDelegate and the uses it as the specification. Please notice the And and Or methods on the specification abstract class. These methods use the extension methods from the ExpressionExtentionGateway to allow the specifications expression data structure to be combined to create a more complex specification.

    public abstract class ExpressionSpecification<T> : IExpressionSpecification<T>
    {
 
        public bool IsSatisfiedBy(T value)
        {
            var x = Predicate.Compile();
            return (x(value));
        }
 
        public Expression<Func<T, bool>> Predicate
        {
            get;
            internal set;
        }
 
        public IExpressionSpecification<T> And(IExpressionSpecification<T> other)
        {
            this.Predicate = this.Predicate.And(other.Predicate);
            return this;
        }
 
        public IExpressionSpecification<T> Or(IExpressionSpecification<T> other)
        {
            this.Predicate = this.Predicate.And(other.Predicate);
            return this;
        }
    }

Expression Extensions

These extension methods extend the Expression object and allow extention object to be combined with “And” and “Or” logic.

    public static class ExpressionExtentionGateway
    {
        public static Expression<Func<T, bool>> Or<T>(
            this Expression<Func<T, bool>> expr1,
            Expression<Func<T, bool>> expr2)
        {
            var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());
            return Expression.Lambda<Func<T, bool>>
                  (Expression.Or(expr1.Body, invokedExpr), expr1.Parameters);
        }
 
        public static Expression<Func<T, bool>> And<T>(
            this Expression<Func<T, bool>> expr1,
            Expression<Func<T, bool>> expr2)
        {
            var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());
            return Expression.Lambda<Func<T, bool>>
                  (Expression.And(expr1.Body, invokedExpr), expr1.Parameters);
        }
    }

Customer Specifications

These specifications are very simple examples of what is possible with the Lamda expression syntax that is now available to you when you use the IExpressionSpecification<T>.

    public class CustomersNamedAdamSpecification : ExpressionSpecification<Customer>
    {
        public CustomersNamedAdamSpecification()
        {
            this.Predicate = c => c.FirstName == "Adam";
        }
    }
 
    public class CustomersInLondonSpecification : ExpressionSpecification<Customer>
    {
        public CustomersInLondonSpecification()
        {
            this.Predicate = c => c.City == "London";
        }
    }
 
    public class GoodCustomersInLondon : ExpressionSpecification<Customer>
    {
        public GoodCustomersInLondon()
        {
            this.Predicate = (new CustomersInLondonSpecification().And
                (new CustomersNamedAdamSpecification())).Predicate;
        }
    }

Using the Specification

The expressions are now available to be compiled and used in the IsSatisfiedBy method and is usable when you pass the expression to a LINQ collections method like FindAll and Where.

    List<Customer> customerList = LoadCustomers();
 
    //Using the specification with the method IsSatisfiedBy
    CustomersInLondonSpecification londonCustomerSpecification =                 
         new CustomersInLondonSpecification();
    foreach (Customer c in customerList)
    {
        Console.WriteLine(londonCustomerSpecification.IsSatisfiedBy(c));
    }
 
    //Using the specification to select items from a list
    IQueryable<Customer> selectedCustomers = customerList.AsQueryable()
        .Where<Customer>(londonCustomerSpecification.Predicate);
 
    foreach (Customer c in selectedCustomers)
    {
        Console.WriteLine("The customer {0} {1} is located in {2}.",
            c.FirstName, c.LastName, c.City);
    }

Conclusions

With the use of Expression data structures, validation and selection specifications are easy to create and are also very easy to test in isolation.


Adam J Wolf

The Intersection of the Arts and Crafts Esthetic and Programming