The Minimalist Guide To Developing Apps

The other day, I was discussing with William how the enthusiasm for a new project tempts us to rush into a project with a list of features, rather than stopping to make a Wireframe, a very important step that saves much time and aggravation.

I’ve never heard of a contractor who builds homes without some form of schematic. The borders of the property need to be mapped out, the lines must be drawn, and the project must be visualized before the first hole is dug. Imagine being halfway through a project when you realize the bathroom is on the wrong side of the house. Whoops.

In software development, a wireframe is a very useful tool and can be created with minimal effort on the back of a napkin, but there are also some very good tools out there that give you a more modern representation. These aid in the understanding of information design, navigation design, and interface design. A good wireframing tool lays out all the buttons and menus and lets you click and drag them into place. Easy peasy.

The mere process of sketching out your website helps you add and subtract features to fit the scope of a project by giving priority to the kinds of information that are displayed and the range of functions that will be available. It goes beyond a mere list, which always gets bigger as the project moves forward, and projects that start that way almost always go over time, as well as over-budget.

There are several wireframe tools out there, both free and paid versions (see below). Paid versions are often more mature and have larger list of features. Free versions are generally newer and are working hard past the awkward teenage years in order to become a paid version. Either way, the mere act of creating a wireframe will save you much time, effort, and aggravation.

Just as web applications need good planning, so do Mobile Applications.  JQuery Mobile has a fun schematic markup on their homepage that gets you thinking about Mobile Development.  They have helped names like Disney and IKEA and allow you to quickly adapt a standard website into a mobile version of your site.

These tools do allow you to upload images to gain a more detailed rendering, but in some ways that defeats the purpose. A black and white representation is often best to grasp work flow and will help you to own the project before you launch development.

Below is a video example from Balsamiq:

Of course this is a good exercise to perform with the developer, but you might even try doing it yourself beforehand.  It’s a simple process that won’t take too much time, but will always give you a return, benefiting both you and your developer.

WireFrame References:
Free Service: Moqups
Paid Services: Mockingbird, Balsamiq


Mobile Apps – How To Save Thousands of Dollars

The gold rush is on, and people have hitched their wagons to many different platforms as they pursue the mobile market. The tsunami of technology is hitting us so fast that consumers are both dazed and engaged as new technologies flood their mobile widget du jour. Even more confused are the companies trying to decide what is best for their organization. Trends are being directed by the market as it is played out through supply and demand. The question boils down to our clients in how should they think about Mobile?

Many are asking, “why do we have different concerns for different platforms: the Web, Mobile Web, and Native Apps? What should mobile web be?”

The good news is that it’s more a buffet than a battle – and under the sneeze guard you can choose options based on how you wish your viewers to engage. Do you wish for them to shop, search, entertain, manage, inform, navigate, or connect? Is security your focus or functionality – or both? What is your budget and where should you invest?

Your Choices:
Mobile web (MW) – This is a browser-based application that is not downloaded from an app store and accessed when you type the URL on your mobile device. It allows fluid browsing, but developers need to code through a web-to-native abstraction layer to enable access to device capabilities that are not accessible in Mobile Web applications, such as the GPS, camera, and local storage.

Native App (NA) – This is an application designed to run specifically on the mobile device and allows use of Native Applications like the device camera, GPS, etc.

NA’s can do more heavy lifting with no need to download cookies because everything is loaded on your device, which provides added security and speed in contrast to a MW, which has traditionally been Read-only.  Still, NA’s are also much costlier to develop and need to be almost entirely coded for each device (Android, Blackberry, iPhone, etc..). Adding iPad compatibility, for example, can add up to 50%, due to the development cost. This provides less flexibility when new technology arrives. In contrast, having an out-of-date MW App is virtually impossible because it naturally adapts to the device.

Twitter and LinkedIn have also invested in both MW and NA. Compare the two iPhone screen shots and try to guess which is which:

Twitter:

LinkedIN:

Technology for MW is improving to a degree that it will soon be undetectable to the user.  Hint: Twitter MW is on the left, LinkedIn MW is on the right.  How did you do?

Compare the difference of the location of the tool bars; how do they act when you touch them? Which one is faster? Do they have the same number of functions?  Will they both allow you to upload a photo?

Boston Globe is another example of a website that has taken a hybrid approach, developing both MW and NA.  Their website is very mobile-friendly, adapting screen size extremely well using HTML-5. One way to test this on your screen is to play with the size of your browser while engaging with BostonGlobe.com. The responsive design is quite deliberate and well done.

The big mistake is to force a traditional media strategy into the mobile environment.  Companies need to realize that the world, and even the Web itself, have changed and continues to change quickly.  One advantage of MW is that it has the potential to adapt quickly and with less impact on your budget.  It is no longer the 2nd class citizen of mobile development and could overtake the NA, though Apple’s dominance should not be underestimated.  Consumers love the one-stop-shopping in the App Store, where credit card numbers are stored in one place.  They also like the one-click icons.

But if you ask, “What should Mobile Web be?”  Soon, it can be whatever you want it to be.  MW has as many advantages as Native Apps and should be equally considered.  My opinion is that developing web apps with the idea of using Cordova to make them native is the most cost effective solution for a customer.  It also delivers a good experience in both platforms.

Read this and this for more on this topic.


How Safe is Your Web Service

You are probably using several software applications that talk to each other.  Whether you have a custom web application or prepackaged financial solution, getting applications and services to communicate requires a skill, technique, and knowledge to protect your information.  So, what happens when your web service is not secure? What information could you be leaking and how could you be vulnerable?

Security Concerns

The four concerns of web service security are privacy, message integrity, authentication, and authorization.

  • Privacy refers to ensuring that messages are not visible to anyone except the web service and the web service consumer. Traffic should be encrypted so that machines in the middle cannot read the messages.
  • Message integrity provides a guarantee that the message received has not been tampered with during transmission.
  • Authentication provides assurances that the message originates from where it claims it did. Both a legal term as well as a technical term, non-repudiation refers to the concern of not only authenticating a message, but proving the origin of that message to other parties.
  • Authorization refers to ensuring that only consumers who should have access to a resource of your web service actually have access to that resource. Authorization requires authentication because without authentication an attacker could pretend to be a highly privileged user.

Building a web service or API (application programming interface) requires a methodology for exchanging secure information, and there are two popular solutions: SOAP and REST.

Technology Choices

Simple Object Access Protocol (SOAP) is a popular protocol specification. It is a complicated specification and some developers, though well-meaning, leave security vulnerabilities.  An example of a vulnerability is SOAP injection. What is SOAP injection? It occurs when the server attempts to parse the XML message from a client. If the XML message is malformed, meaning that it does not follow the rules that the server expects it to follow, the server may return an error message that actually shows code and gives insight into the underlying system. Developers may turn off this behavior. However, this is often forgotten before a deployment.

REST (Representational State Transfer) is an architectural style for distributed systems. The World Wide Web is one such distributed system. REST has become a popular architectural choice for designing web services. Such web services are referred to as RESTful web services. An advantage of using REST is that the security vulnerabilities are well known as they are the same vulnerabilities that impact web sites. This means that developers who are familiar with website security will be able to leverage their knowledge to secure RESTful web services.

Final Thoughts

Developers working with either of these technologies must be concerned with the four security points. No methodology or architectural choice ensures that your information is well-protected. It is important that your consultants explain the architecture they plan to use and how their implementation plan accounts for security concerns. If your developer does not have a detailed answer, it is a red flag.


ASP.NET MVC Domain Driven Design Deux

Series Navigation

  1. Setup
  2. Mapping and Entity Equality

Entity Equality

We’ve got some more housekeeping to do on our Entity object before proceeding.  Because entities are comparable based upon Id, a standard use of the == operator will produce undesirable results. When using an ORM, this is particularly important. You will often have instances of objects, especially objects in child relationships, that are the same as, but not reference equal to, one another.

Test Cases for Desired Entity Equality Behavior

I’m a believer in documentation via test cases, so here are my test cases that demonstrate the desired behavior:


[TestFixture]
public class EntityEqualityContext
{
[Test]
public void TwoTransientEntitiesShouldNotBeEqual()
{
var entity1 = new TestEntity();
var entity2 = new TestEntity();

Assert.AreNotEqual(entity1, entity2, “Different transient entities should not be equal.”);
}

[Test]
public void TwoReferencesToSameTransientEntityShouldBeEqual()
{
var entity1 = new TestEntity();
var entity2 = entity1;

Assert.AreEqual(entity1, entity2, “Two references to the same transient entity should be equal.”);
}

[Test]
public void EntitiesWithSameIdShouldBeEqual()
{
var entity1 = new TestEntity();
var entity2 = new TestEntity();

entity1.SetId(1);
entity2.SetId(1);

Assert.AreEqual(entity1, entity2, “Entities with same id should be equal.”);
}

[Test]
public void EntitiesWithDifferentIdShouldNotBeEqual()
{
var entity1 = new TestEntity();
var entity2 = new TestEntity();

entity1.SetId(1);
entity2.SetId(2);

Assert.AreNotEqual(entity1, entity2, “Entities with different ids should not be equal.”);
}

[Test]
public void EntityShouldNotEqualTransientEntity()
{
var entity1 = new TestEntity();
entity1.SetId(1);

var entity2 = new TestEntity();

Assert.AreNotEqual(entity1, entity2, “Entity and transient entity should not be equal.”);
}

[Test]
public void EntitiesWithSameIdButDifferentTypesShouldNotBeEqual()
{
var entity1 = new TestEntity();
var entity2 = new OtherEntity();

entity1.SetId(1);
entity2.SetId(1);

Assert.AreNotEqual(entity1, entity2, “Entities of different types should not be equal even if they have the same id.”);
}

///

/// A test entity class created so that we can excercise
/// the functionality of the entity equaltiy members.
///

 

public class TestEntity : Entity
{
private int id;

public override int Id
{
get { return id; }
}

public void SetId(int id)
{
this.id = id;
}
}

public class OtherEntity : Entity
{
private int id;

public override int Id
{
get { return id; }
}

public void SetId(int id)
{
this.id = id;
}
}
}

Summarized, these tests say that entities with id of “0” should only be equal if they are the same object.  This is reference equality.  Entities with an id should be equal if their ids are equal and they are of the same type.  This is identity equality.

Entity with Equaltiy Members


public abstract class Entity: IEquatable
{
private int id;
private int transientHashCode;

public virtual int Id { get { return id; } }

public override bool Equals(object obj)
{
return Equals(obj as Entity);
}

public virtual bool Equals(Entity obj)
{
if (obj == null) return false;

if (IsTransient)
{
return ReferenceEquals(this, obj);
}

return obj.Id == Id && obj.GetType() == GetType();
}

public override int GetHashCode()
{
if (IsTransient)
{
if (transientHashCode == 0)
{
transientHashCode = base.GetHashCode();
}
return transientHashCode;
}
return id;
}

private bool IsTransient
{
get { return Id == 0; }
}
}

For more information about why insuring that your entity equality is in order, please see The NHibernate FAQ.

As this is a blog example, we will need a class to represent posts.

The Post Class


public class Post : Entity, IEquatable
{
public virtual string Title { get; set; }

public virtual string Body { get; set; }

///

/// Indicates whether the current object is equal to another object of the same type.
///

 

///
/// true if the current object is equal to the parameter; otherwise, false.
///
////// An object to compare with this object.
/// public virtual bool Equals(Post other)
{
return base.Equals(other);
}
}

In the future, we will add other properties like a collection of comments.  For now, we will keep it simple in order to demonstrate the fluent mapping.

What’s the Deal with the Virtual Members

NHibernate makes use of proxies for advanced features like lazy loading.  The default proxy factory uses Castle’s DynamicProxy. DynamicProxy generates inheritance based proxies; therefore, it can only work if members are marked as virtual so that it can override them.  There are other proxy choices; however, I will not be covering them. Making members virtual is a small price to pay for the convenience in my opinion.

Mapping the Post Entity to the Database

Generating the mappings for your entities could not be easier with fluent NHibernates automapper.

Here is a simple utility class to add to the Service project:


public class DomainMapper
{
private readonly IPersistenceConfigurer persistenceConfigurer;

public DomainMapper(IPersistenceConfigurer persistenceConfigurer)
{
this.persistenceConfigurer = persistenceConfigurer;
}

public void Configure(Configuration configuration)
{
Fluently.Configure(configuration).Mappings(mapping => mapping.AutoMappings.Add(GetMapper())).Database(
persistenceConfigurer).BuildSessionFactory();
}

protected virtual AutoPersistenceModel GetMapper()
{
var persistenceModel = new AutoPersistenceModel(typeof (Entity).Assembly)
.Where(type => !type.IsAbstract && typeof (Entity).IsAssignableFrom(type))
.WithConvention(convention =>
{
convention.IdConvention =
id => id.Access.AsReadOnlyPropertyThroughCamelCaseField().GeneratedBy.HiLo(100.ToString());
convention.IsBaseType = type => type == typeof (Entity);
convention.DefaultStringLength = 255;
});
return persistenceModel;
}
}

I like to use HiLo for the id convention and avoid using Native Identity.  For more information about the identity generators available using NHibernate, please see Vadi’s Rants.

The DefaultStringLength is just a personal preference.  The default is 100 if you do not specify a convention.

The IsBaseType is necessary so fluent NHibernate does not create joined table entities from everything that inherits from Entity.

In the Blog.Service.Test project, add this utility class:


public class TestDomainMapper: DomainMapper
{
public TestDomainMapper() : base(SQLiteConfiguration.Standard.InMemory().ShowSql())
{
}
}

This class simply inherits from DomainMapper and provides a SQLite in memory database as the persistence configuration.  Using an in-memory database for our tests will make them run much faster.  As the project grows, it is advisable to also run your integration tests vs the actual database that you will be using; however, running them against an in-memory database during standard development saves time and is very convenient.

In my first post, I attempted to make a thorough list of the tools that would be used in the project.  I neglected at least one though: SQLite.  I may have neglected more, so do not be surprised if we have to add more binaries throughout the series to our libraries directory.  System.Data.SQLite can be downloaded here.  Add it to trunk/libraries/sqlite and reference it from the Blog.Service.Test project.

Fluent NHibernate provides a useful helper for integration tests: PersistenceSpecification<T>.  Here is what the initial Post integration test looks like:


[TestFixture]
public class MappingIntegrationContext
{
protected ISession Session { get; private set; }

[SetUp]
public void BeforeEachTest()
{
var configuration = new Configuration();
new TestDomainMapper().Configure(configuration);

var sessionFactory = configuration.BuildSessionFactory();
Session = sessionFactory.OpenSession();

IDbConnection connection = Session.Connection;

string[] scripts = configuration.GenerateSchemaCreationScript(Dialect.GetDialect(configuration.Properties));
scripts.ToList().ForEach(script =>
{
var cmd = connection.CreateCommand();
cmd.CommandText = script;
cmd.ExecuteNonQuery();
});

Session.Flush();
}

[Test]
public void PostIntegrationTest()
{
new PersistenceSpecification(Session)
.CheckProperty(x => x.Title, “A Test Post”)
.CheckProperty(x => x.Body, “This is where the content of my post will be. Yay.”)
.VerifyTheMappings();
}
}

This is a good start, but obviously as our domain model grows and we need more test classes, this SetUp can be abstracted into its own base class that other test classes can inherit from.


public abstract class FixtureBase
{
[SetUp]
public void BeforeEachTest()
{
var configuration = new Configuration();
new TestDomainMapper().Configure(configuration);

var sessionFactory = configuration.BuildSessionFactory();
Session = sessionFactory.OpenSession();

IDbConnection connection = Session.Connection;

string[] scripts = configuration.GenerateSchemaCreationScript(Dialect.GetDialect(configuration.Properties));
scripts.ToList().ForEach(script =>
{
var cmd = connection.CreateCommand();
cmd.CommandText = script;
cmd.ExecuteNonQuery();
});

Session.Flush();
}

protected ISession Session { get; private set; }
}

Now the noise of the SetUp method can be taken out of the MappingIntegrationContext and we have a reusable base class for future test classes.

Implementing IRepository

Next, we will implement our repository.  NHibernate.Burrow AppBlock makes this trivial.  Reference NHibernate.Burrow.AppBlock from the Blog.Service assembly.


using System.Collections.Generic;
using Blog.Domain;
using NHibernate.Burrow.AppBlock.DAOBases;

namespace Blog.Service
{
public class Repository: GenericDAO, IRepository where T : Entity
{
///

/// Find an entity by unique identifier.
///

 

///Unique identifier of the entity. /// Entity if found, null otherwise.
public T Find(int id)
{
return base.Get(id);
}

///

/// Find all entities.
///

 

/// Sequence of entities found.
public new IEnumerable FindAll()
{
return base.FindAll();
}

///

/// Save (insert or update as appropriate) on next commit of the unit of work.
///

 

///Entity to be saved. public new void Save(T entity)
{
base.Save(entity);
}

///

/// Delete on next commit of the unit of work.
///

 

///Entity to be deleted. public new void Delete(T entity)
{
base.Delete(entity);
}
}
}

For the basic functionality, AppBlock provides everything that we need.

Update: Some of you want the sample project that I am working from, so I will add a zip of it soon.

In the next post, we will wire up the Inversion of Control in our MVC app and create a controller for Post CRUD.

kick it on DotNetKicks.com

ASP.NET MVC Domain Driven Design

Series Navigation

  1. Setup
  2. Mapping and Entity Equality

Introduction

In this series of posts, I will detail how I set up projects using the principles of domain driven design in ASP.NET MVC.

The tools and libraries we will use are as follows:

The sample app will be the canonical blog example. This series will be light on the discussion of the theory of DDD and heavy on the nuts and bolts of asp.net MVC implementation.

Project Structure

Create a new directory for the project.  I’m calling mine DDDSample. Following subversion convention, create a trunk and branches folder inside of DDDSample. Inside of trunk, create three directories: src, tools, and libraries.

The ‘src’ directory is where our code will go. The ‘tools’ directory will have NUnit and in the future, NAnt. The ‘libraries’ directory will contain the third party binaries that the project references.

Gathering the Libraries and Tools

1) Download the latest binary of fluent nhibernate from http://fluentnhibernate.org/downloads. Put the fluent nhibernate binaries in trunk/libraries/fluent-nhibernate.

2) Download NHibernate.Burrow from http://sourceforge.net/project/showfiles.php?group_id=216446. Put the burrow binaries in trunk/libraries/nhibernate.burrow. Important Note: Sometimes the latest version of NHibernate.Burrow will not have been built against the same version of NHibernate as fluent nhibernate was. Therefore, it is important that you be able to build NHibernate.Burrow, and the rest of the libraries that follow, from source.  NHibernate.Burrow is a part of NHContrib. The NHContrib svn repository is located at https://nhcontrib.svn.sourceforge.net/svnroot/nhcontrib/trunk. There is a build script in the root directory of the NHibernate.Burrow subdirectory of the project. To rebuild with a different version of NHibernate, just replace the NHibernate dll in NHibernate.Burrow/lib/NHibernate with the binary of NHibernate from the fluent nhibernate.

3) Download NUnit from http://www.nunit.org/index.php?p=download.  Get the zip distribution. Unzip the entire contents into trunk/tools/nunit. It is important that you include the full NHibernate distribution with your project so when we add an automated build tool later it will be able to run the unit tests without assuming that every developer has installed the correct version of NUnit from msi.

4) Download Moq from http://code.google.com/p/moq/downloads/list. Put the binaries in trunk/libraries/moq.

5) Download MVCContrib from http://www.codeplex.com/MVCContrib. Put the binaries in trunk/libraries/mvccontrib.

As an added measure of safety against change, I like to reference the MVC libraries themselves from binaries I store in my svn repository instead of from source.  You don’t have to do this, but if you choose to, I put System.Web.Mvc, System.Web.Routing, and System.Web.Abstractions in trunk/libraries/mvc.

Your completed project structure should look like this:

Creating the Projects

Our mvc project and class libraries will go in trunk/src.

Create an asp.net MVC project.  For this sample, I’m calling mine Blog.Web.

Create two class libraries: Blog.Domain and Blog.Service. Blog.Domain is where our POCO (Plain Old C# Objects) entities and our repository interfaces will reside. Blog.Service is where the business logic that ties the application together will live.

Reference Blog.Domain and Blog.Service from Blog.Web. Reference Blog.Domain from Blog.Service.

Create a new solution folder (right click on project, hover over add, choose new solution folder) called Test. This is where our test projects will go.

Create three class libraries: Blog.Web.Test, Blog.Domain.Test, and Blog.Service.Test.  In each of these projects reference NUnit.Framework from /trunk/tools/nunit.

More test projects may be needed later for separating unit tests from integration tests, but this is how I like to start with one unit test project for each of my projects.

The solution should now look like this:

Entity Base Class

In the domain, create an object to be the base class for entities. An entity is an object that has an identity.

namespace Blog.Domain
{
public abstract class Entity
{
private int id;

public virtual int Id { get { return id; } }
}
}

There is no way to set the id property of the Entity base class. This is by design. Our persistence layer will use NHiberante generators to generate the identity values when we save new entities to the database.

Repositories

Just what are repositories? Repositories are an abstraction of the way we manage aggregates. Repositories should correspond only to aggregate roots.  An aggregate is a cluster of objects that are treated as a unit.  The aggregate root is the root object of the unit.

In Domain Driven Design, the repository interfaces are a part of the domain, but the implementations are not.

Generic Repository of Entities

All entity repositories will need some base functionality, so we define IRepository<T> with some basic methods that we expect any repository to need.

using System.Collections.Generic;

namespace Blog.Domain
{
///

 

/// Repository of entities.
///

 

 

public interface IRepositorywhere T : Entity
{
///

 

/// Find an entity by unique identifier.
///

 

 

///Unique identifier of the entity. /// Entity if found, null otherwise.
T Find(int id);

///

 

/// Find all entities.
///

 

 

/// Sequence of entities found.
IEnumerable FindAll();

///

 

/// Save (insert or update as appropriate) on next commit of the unit of work.
///

 

 

///Entity to be saved. void Save(T entity);

///

 

/// Delete on next commit of the unit of work.
///

 

 

///Entity to be deleted. void Delete(T entity);
}
}

Conclusions

In this post we have done a lot of nuts and bolts work. The amount of setup required may seem daunting, but as stated earlier, the third party tools and libraries will pay dividends in the long-run.

In the next post, we will create a Post entity, create a concrete implementation of IRepository<Post> using NHibernate, map Post to a database using Fluent NHibernate, and test our persistence model.

kick it on DotNetKicks.com

Register Repository Implementations Automatically with a Castle Facility

Isn’t it annoying to have to register all your repository implementations by hand? When you get to a certain number of them, it becomes quite a task. If you want to register them for multiple interfaces, it gets even worse.

When using Windsor as your inversion of control container, separating your repository registrations into a facility is a good start.  In general though, all our repositories follow a simple pattern and should be easily registrable automatically following an algorithm.

Domain driven design tells us that the repository interfaces are a part of the domain but the implementations are not.  Therefore, we usually have two assemblies that are important.

This is a typical project layout:

Our facility needs to allow us to configure what assemblies it searches for types and the base type of the repository.

Specification

Here is a simple test describing the desired behavior:


[TestFixture]
public class RepositoryRegistrationFacilityTestFixture
{
[Test]
public void ShouldRegisterCustomerRepository()
{
var kernel = new Castle.MicroKernel.DefaultKernel();

var facility = new RepositoryRegistrationFacility(typeof (IRepository<>), typeof (Customer).Assembly);

facility.Init(kernel,
new Castle.Core.Configuration.MutableConfiguration(“facility-config”));

kernel.Resolve().ShouldBeInstanceOfType(typeof (CustomerRepository));
kernel.Resolve<IRepository>().ShouldBeInstanceOfType(typeof (CustomerRepository));

}

protected interface IRepository
{
}
protected interface ICustomerRepository : IRepository
{
}
protected class CustomerRepository : ICustomerRepository
{
}
protected class Customer
{
}
}

Implementation


public class RepositoryRegistrationFacility : AbstractFacility
{
private readonly Assembly[] assemblies;
private readonly Type genericRepositoryType;

public RepositoryRegistrationFacility(Type genericRepositoryType, params Assembly[] assemblies)
{
this.assemblies = assemblies;
this.genericRepositoryType = genericRepositoryType;
}

protected override void Init()
{
Predicate isGenericRepositoryInterface =
type =>
type.GetInterfaces().Contains(
x => x.IsGenericType && x.GetGenericTypeDefinition().IsAssignableFrom(genericRepositoryType));

IEnumerabletypes =
assemblies.Aggregate(Enumerable.Empty(), (accumulator, assembly) => accumulator.Concat(assembly.GetTypes()));

IEnumerablerepositoryInterfaces = types.Where(
type => type.IsInterface && !type.IsGenericTypeDefinition && isGenericRepositoryInterface(type));

repositoryInterfaces
.ForEach(interfaceType =>
{
Type implementor =
types.FirstOrDefault(type => interfaceType.IsAssignableFrom(type) && !type.IsAbstract);
if (implementor == null) return;

IEnumerablegenericRepositoryInterfaceTypes = implementor.GetInterfaces().Where(
x =>
x.IsGenericType &&
x.GetGenericTypeDefinition().IsAssignableFrom(genericRepositoryType));

Kernel.Register(
Component.For(interfaceType).ImplementedBy(implementor).Forward(
genericRepositoryInterfaceTypes));
});
}
}

Now in fluent configuration you can just do this:

container.AddFacility("persistent-repository-facility", new RepositoryRegistrationFacility(typeof(IRepository<>), typeof(IRepository<>).Assembly, typeof(SomethingRepository).Assembly));

I have not tested the binsor registration, but you should be able to do something like this to register it using binsor:

facility RepositoryRegistrationFacility:
genericRepositoryType: IRepository
assemblies: array(System.Reflection.Assembly, IRepository.Assembly, SomethingRepository.Assembly)

I hope this is useful.

kick it on DotNetKicks.com


Data Transfer Objects

Data Transfer Objects Pattern

Data Transfer Objects (DTOs) are a necessary time-sink when working with SOA.  Proper SOA dictates that you must not pass domain objects across service boundaries.  In many cases, such as when using an ORM, it is extremely difficult to pass your domain objects across the service boundaries even if you choose to disregard the SOA guidance. Also, there may be good reasons why you do not want to make your domain objects serializable.

DTOs Defined

So what exactly are DTOs?  They are objects that have no behavior outside of accessors and mutators of their properties. Often times DTOs line up one-to-one with domain objects as in the following example.

///

/// Domain Object
///

 

public class Company{
private string name;
private string taxId;
public Company(string name, string taxId) {
this.name = name;
this.taxId = taxId;
}

public string Name { get { return name; } }
public string TaxId { get { return taxId; } }}

///

/// Data Transfer Object
///

 

public class CompanyDTO{
public string Name { get; set; }
public string TaxId { get; set; }}

Other times DTOs may need to carry data for a request that has no direct representation as a single object in the domain. Consider a service that needs to expose data about a company and its owner. Obviously the clients shouldn’t have to request data about the company and then data about the owner in a separate request. Doing so would incur the costs of two round trips, and the owner data is a part of a single logical unit as exposed by the service.


///

/// A company
///

 

public class Company{
private string name;
private string taxId;

public Company(string name, string taxId)
{
this.name = name;
this.taxId = taxId;
}

public string Name { get { return name; } }
public string TaxId { get { return taxId; } }

public Owner Owner { get; set; }}

///

/// Owner of a company
///

 

public class Owner{
public Company Company { get; set; }

public string FirstName { get; set; }
public string LastName { get; set; }}

///

/// Data Transfer Object
///

 

public class CompanyDTO{
public string Name { get; set; }
public string TaxId { get; set; }

public string OwnerName { get; set; }
}

From Domain Object to DTO and Back Again

The assembler pattern, a subset of the mapping pattern, is used to translate DTOs to and from domain objects.

It is possible to create a reusable conventions based assembler. I will talk more about this in the future. For small projects, the cost of creating assemblers for the DTOs is trivial. For larger ones, it is still worth the effort for the sake of encapsulation.

///

/// Assembler for Company and CompanyDTO.
///

 

public interface ICompanyAssembler{
CompanyDTO Convert(Company company);
Company Convert(CompanyDTO DTO);}

What is so useful about an object that has no behavior?

DTOs may seem like weak objects because of their lack of behavior; but this is what makes them the one object that is safe to pass across a service boundary. A client that interacts with your service may, and often will, have a different domain from the service itself. In fact, many different clients with many different domains may interact with your service. It is difficult and undesirable to share the same domain model between a service and all its potential clients.

Consider again the Company example. Let us assume that the service we are writing is a better business bureau catalog of companies. The domain object, Company, may include such methods as “FileComplaint” or “RevokeLicense.”

This service may be consumed by an auction site that wants to use the companies names and ratings but has no need to file complaints and does not have the ability to revoke a license.  The company domain object for the auction site will include methods such as “AddAuction” or “AssociateWithReview.”

Sharing the domain objects between the auction site and the better business bureau service would pollute both domains; not to mention the fact that they may, and in this example certainly would, have different owners who do not wish to share code bases.

Sharing DTOs, because of their lack of behavior, works fine though. The DTOs serve as a simple, abstracted definition for the data that the service and its clients must exchange.

DTOs also insulate your service clients from changes to the domain of the service and vice versa. You are free to change your domain objects as much as you want and leave the DTOs alone. The assembler can simply be updated as the domain objects are updated.

If the domain objects were shared by the clients, every change to a domain object would directly impact clients, greatly increasing the costs of maintaining the service.

kick it on DotNetKicks.com