Roger Alsing Weblog

Composite Oriented Programming: QI4J running on .NET

leave a comment »

For the last month I have been spending my spare time porting the awesome Java framework QI4J to .NET.
QI4J is the brain child of Rickard Öberg and Niclas Hedhman and it attempts to enable Composite Oriented Programming for the Java platform.
(For more info regarding Composite Oriented Programming see the QI4J website: http://www.qi4j.org/ )

I’m well aware that others have been doing spikes on COP for .NET, a few of those attempts can be found here:
http://stackoverflow.com/questions/152196/composite-oriented-programming-cop-net-4-0-mef-and-the-oslo-repository

However, I think it is sad to not reuse all of the effort and brain power that has been put into QI4J, and thus I decided to port it instead.

The code is currently only available from my SVN repository at google code:
http://code.google.com/p/alsing/source/checkout

Please note that the code will be released under the same license as the Java version (Apache License version 2.0)
And copyright notices for the ported code will also be applied to give credit where credit is due.

The .NET version is largely identical to the Java version as it is pretty much a plain class by class port.
However there are a few exceptions:

The concept of “Property<T>” is not available in the .NET version since C# and most .NET languages does support properties out of the box and it would feel awkward to write things like:

“order.Customer.Set(theCustomer)” rather than “order.Customer = theCustomer”

However, the framework does rely on the Property<T> internally and thus most of the state holding infrastructure is also identical to the Java version.

The Java version relies on its own set of query expressions while my plan is to possibly reuse those internally but rather expose a LINQ API for querying.
(I have not yet started to build that)

Currently supported concepts:

Soon to come:

And I will ofcourse post a few samples of what you can do with this ASAP, I just wanted to drop a little sneak peek :-)

//Roger

Written by Roger Alsing

June 25, 2009 at 7:20 pm

Entity Framework 4 – Entity Dependency Injection

with 4 comments

When dealing with a fat domain model, there is often a need to be able to inject different services into your entities.
e.g. you might want to inject some domain service like “ITaxCalcualtorService” or an infrastructure service like “IEmailNotificationService” into your entities.

If we rely completely on eager loading, then this is not a big problem, we can simply let or repositories iterate over each entity once we have fetched them from the DB and inject our services.
But when it comes to Lazy Load, we can no longer do this, in this case we need to get notified by the O/R mapper when an entity have been materialized so that we can inject our services into it.

If you are aiming to use Entity Framework 4 once it is released, you can accomplish this with the following code snippet:


..inside your own EF container class..

public MyContext()
    : base("name=MyContext", "MyModelContainer")
{
    ...
    ObjectStateManager.ObjectStateManagerChanged +=
    ObjectStateManagerChanged;
}

// this handler gets called each time the
// containers statemanager is changed
void ObjectStateManagerChanged(object sender,
                          CollectionChangeEventArgs e)
{
    // we are only interested in entities that
    // have been added to the state manager
    if (e.Action != CollectionChangeAction.Add)
        return;

    var state = ObjectStateManager
                    .GetObjectStateEntry(e.Element).State;

    // we are only interested in entities that
    // are unchanged (that is; loaded from DB)
if (state != System.Data.EntityState.Unchanged)
        return;

    OnEntityMaterialized(e.Element);
}

// this method gets called each time
// an entity have been materialized
private void OnEntityMaterialized(object entity)
{
    if (entity is Order)
    {
        Order order = entity as Order;
        // use property injection to assign
        // a taxcalculator service to the order
        order.TaxCalculatorService =
SomeDIContainer.GetObject<ITaxCalculatorService>();
    }
}

The above is a very naïve example, but it does show how you can catch the materialization of a specific entity type and then configure that entity.

This allows us to add complex domain logic to our entities.
We can for example call a method like: “order.CalculateTotals()” where the CalculateTotals method now uses the ITaxCalculatorService.

HTH.

//Roger

Written by Roger Alsing

May 30, 2009 at 11:35 am

Posted in .NET, Entity Framework, Linq

Entity Framework 4 – “Almost” POCO

leave a comment »

This is a short rant..

I have been very impressed with EF4 so far, but I’ve now found out that EF4 will NOT support enums.
I find this is very strange, I can’t see how Microsoft can claim POCO support and not support one of the most common code constructs.

More info here:

http://social.msdn.microsoft.com/Forums/en-US/adonetefx/thread/7659feab-d348-4367-b2cd-0456b20262fe

Someone might claim that you can create a private property containing the mapped integer value and then make a public property exposing the enum.
But this comes with two major drawbacks:

1) You can’t create Linq queries that are executed at DB level if you use unmapped properties.
The Linq query would have to use the integer property, and thus loosing it’s semantics.

2) That is not POCO, that is mapper requirements leaking all over the place.

Written by Roger Alsing

May 29, 2009 at 8:14 pm

Posted in .NET, Entity Framework

Entity Framework 4 – Using Eager Loading

with 6 comments

When Linq To Sql was released we were told that it did support eager loading.
Which was a bit misleading, it did allow us to fetch the data we wanted upfront, but it did so by issuing one database query per object in the result set.
That is, one query per collection per object, which is a complete performance nightmare. (Ripple loading)

Now in Entity Framework 4, we can actually do true eager loading.
EF4 will issue a single query that fetches the data for all the objects in a graph.
This have been possible in other mappers for a long time, but I still think it is awesome that Microsoft have finally listened to the community and created a framework that from what I’ve seen so far, does exactly what we want.

So how do you use eager loading in EF4 ?

Eager loading is activated by calling “ObjectSet[of T].Include(”Details.Product”)”, that is, a dot separated property path.
You can also call include multiple times if you want to load different paths in the same query.

There are also a few attempts out in the blog world to try to make it easier to deal with eager loading, e.g. by trying to remove the untyped string and use lambda expressions instead.

I personally don’t like the lambda approach since you can’t traverse a collection property that way; “Orders.Details.Product” , there is no way to write that as a short and simple lambda.

My own take on this is to use extension methods instead.
I always use eager loading on my aggregates, so I want a simple way to tell my EF context to add the load spans for my aggregates when I issue a query.
(Aggregates are about consistency, and Lazy Load causes consistency issues within the aggregate, so I try to avoid that)

Here is how I create my exstension methods for loading complete aggregates:


public static class ContextExtensions
{
  public static ObjectQuery<Order>
           AsOrderAggregate(this ObjectSet<Order> self)
  {
    return self
        .Include("Details.ProductSnapshot")
        .Include("CustomerSnapshot");
  }
}

This makes it possible to use the load spans directly on my context without adding anything special to the context itself.
(You can of course add this very same method inside your context if you want, I simply like small interfaces that I can extend from the outside)

This way, you can now issue a query using load spans like this:


var orders = from order in context.OrderSet.AsOrderAggregate()
             select order;

And if you want to make a projection query you can simply drop the “AsOrderAggregate” and fetch what you want.

HTH.

//Roger

Written by Roger Alsing

May 24, 2009 at 3:36 pm

Entity Framework 4 – Managing inverse properties

with 4 comments

[EDIT]
I was wrong!

It is perfectly possible to do one directional associations in EF4 and POCO mode.
You simply have to manually remove the “ <NavigationProperty ..” tags from your mapping files.

Awesome work EF4 design team :-)

[/EDIT]

Original post:
To my surprise I’ve found out that Entity Framework 4 don’t support one directional collection properties.
That is, if you have the entity “Order” which has an “Details” property, then the “OrderDetail” entity _must_ have an “Order” property.

To make things worse, those properties do not have any auto sync mechanism if you are using POCO entities.
They could very well have supported this by adding an inverse management aspect to their run-time proxies that they use for lazy loading in POCO.

While I do think this is a lacking feature, it is not really a show stopper for me.
We can work around this problem by applying the “Law of Demeter” principle.

We can design our entities like this:

OrderDetail:


public class OrderDetail
{
    ...properties...

    [Obsolete("For EF4 Only!",true)]
    public OrderDetail()
    { }

    public OrderDetail(Order order)
    {
        this.Order = order;
    }
}

Order:


public class Order
{
    ...properties...

    public void AddProduct(Product product,
                                   double quantity,
                                   double itemPrice)
    {
        var detail = new OrderDetail(this)
        {

//offtopic: you might want to associate
//the product via ID or via a snapshot instead
//depending on how you deal with cross aggregate references
            Product = product,

            Quantity = quantity,
            ItemPrice = itemPrice,
        };

        Details.Add(detail);
    }
}

This way, we get a whole bunch of positive effects:

We solve the problem with inverse properties, inverse management is handled inside the “AddProduct” method in the order.

We get a nice way to handle consistency in our aggregate roots, the methods can easily update any accumulated values in the order or change status of the order when we add or remove order details.
This is what aggregates in DDD is all about so you should probably do this anyway, regardless if EF4 did support inverse property management or not.

We add domain semantics to the model, “AddProduct” or “ChangeQuantity” have meaning in our model, thus we get a more self explaining model.

This is a quite nice example of how lacking framework features can force you to write better code.
If we did have support for inverse property management, we might get sloppy and just go the path of least resistance.

//Roger

Written by Roger Alsing

May 22, 2009 at 10:04 am

Entity Framework 4 – Where Entity.Id in Array

with 2 comments

Here is a little trick if you want to issue a query to the database and select a batch of entities by ID only:


//assemble an array of ID values
int[] customerIds= new int[] { 1, 2, 3 };

var customers = from customer in context.CustomerSet
                where customerIds.Contains(customer.Id)
                select customer;

This will make Entity Framework issue an SQL query with the where clause “where customerId in (1,2,3)”, and thus, you can batch select specific entities with a single query.
I will get back to this idea in a later post because this is related to how I design my entities and aggregates in DDD.

//Rogerr

Written by Roger Alsing

May 21, 2009 at 7:06 pm

Entity Framework 4 – Immutable Value Objects

leave a comment »

Ok, the title is not quire accurate, I’m not aware of any way to accomplish truly immutable types for Entity Framework.

However, this is a quite nice attempt IMO:


    public class Address
    {
        //Private setters to avoid external changes
        public string StreetName { get;private set; }
        public string City { get; private set; }
        public string ZipCode { get; private set; }

        //Provide a default ctor for EF4
        [Obsolete("For EF4 Only",true)]
        public Address() {}

        //Force values to be set via ctor.
        public Address(string streetName, string city, string zipCode)
        {
            StreetName = streetName;
            City = city;
            ZipCode = zipCode;
        }

        ...equality overrides and such...
    }

This works very well with Entity Framework 4 and I think it is a fair compromise.

//Roger

Written by Roger Alsing

May 21, 2009 at 4:27 pm

Entity Framework 4 – First Impressions

leave a comment »

I downloaded the VS 2010 beta1 today and started to dissect Entity Framework 4.

(Also note the name: EF4.. The new name comes from .NET _4_ )

Here are my initial impressions:

POCO Support.

POCO comes in two flavors: Run-time POCO and Compile-time POCO:

Run-time POCO is where the framework interact with your POCO types directly.
This approach lacks support for lazy load due to the fact that there is no lazy loading code in your POCO classes.

Compile-time POCO is where the framework create run-time proxies on-top of your POCO entities and applies the lazy load support inside the proxies.
Thus, the entities used in run-time are far from POCO.

The POCO support also include ValueObjects, so you can map POCO value objects too.

I’m very pleased to see that these features are finally coming.
(We did have this in NPersist in 2005, but it’s still nice ;-) )
 

Lacking support for extensibility.

This was both expected and sad to see at the same time.
The entire materialization mechanism of EF4 is black boxed, there are no extension points at all.

I was hoping for some materialization event where one could override the default object creation process.
And thus apply more behaviors to the objects, e.g. via NAspect and proxify the entities even more.

(This feature is missing from Linq to Sql and MEF too, so I wasn’t too surprised)

 

Design by Contract .

This is not really a feature of EF4 but rather of .NET framework 4.
But as far as I can tell, contracts seems to work fine within your entities.
I still need to do a few more tests and see how well the contracts play with the run-time proxies though.
More to come in later posts…

Written by Roger Alsing

May 21, 2009 at 3:24 pm

Pleasing the O/R Mapper – Default Constructor Hack

with 2 comments

Hack of the day:

Most O/R mapper frameworks require entities to implement a default constructor.

This is most often not a big deal, most entities would support a default constructor no matter if the mapper needed it or not.
However, if you intend to expose an entity that only support a copy constructor.

Let’s say for the sake of the argument that we have an immutable “Order” class, that can only be created by passing an “OrderRequest”:


public class Order
{
   public Order( OrderRequest request )
   {
         this.Customer = request.Customer;
         this.Details =
                  request
                  .Details
                  .Select ( requestDetail => 
                                new OrderDetail (requestDetail))
                  .ToList();
         ...
   }

   ....
}

No matter if the order is only partially or completely immutable, you want to force developers to instantiate the order by the above constructor.

But if the mapper forces you to supply a default constructor, then you can no longer guarantee that the class is used correctly.

So what can be done about it?

I’ve come up with a hack that prevents this problem, but be aware that this is a pure hack ;-)
You can provide a default constructor and mark it with the “Obsolete” attribute.

This can prevent your code from calling the constructor while allowing the mapper framework to create the entities through reflection (which most POCO mappers already do).
You can even separate out this hack code from the actual entity using partial classes:


public partial class Order
{
   public Order( OrderRequest request )
   {
         this.Customer = request.Customer;
         this.Details =
                  request
                  .Details
                  .Select ( requestDetail => 
                                new OrderDetail (requestDetail))
                  .ToList();
         ...
   }

   ....
}

--other file--

public partial class Order
{
     [Obsolete("For NHibernate use only!",true)]
     public Order() {}
}

To keep the hack code away and a safe distance from the actual implementation you could place all those partial default ctor snippets in a separate file or so.

e.g. “NHibernateHack.cs” or something similair.

Also note that for NHibernate, there are other options see: http://nhforge.org/blogs/nhibernate/archive/2008/12/12/entities-behavior-injection.aspx

But this trick is applies to any mapper that creates instances through reflection and requires a default ctor.
Or maybe this is an old trick, but it does fill it’s purpose.

//Roger

Written by Roger Alsing

May 11, 2009 at 5:02 pm

Posted in .NET, C#, O/R Mapping

The simplest form of configurable Dependency Injection

with 12 comments

I love the concept of dependency injection, but I’ve never found a dependency injection framework that I think is easy enough to use.

They either rely on XML configurations that are really awkward.
Others have force you to resolve objects by some untyped string ID.

I don’t want that.
I want to resolve my objects through normal methods, that’s intuitive and the code becomes readable too.

However, if you try to accomplish this by code without writing yet another framework.
You will either have to decide if you want your resolver to have static or instance methods.

If you go for instance methods, then you will have to make some sort of factory for the factory itself if you want to be able to return other implementations of the same factory.

If you go for static methods, you will probably end up with a static dead factory that you can’t change in run-time, since that’s the nature of static methods.

I personally like the simplicity of the static methods, but as I said, they are not configurable.

But there is a quite slick solution to this problem;
I have started to use static delegates for this instead.

By exposing static delegates I can get the same simplicity as when calling static methods, but
at the same time achive the pluggability of instance methods (or rather of different implementations of the same factory).

Here is some sample code:


//The Class that you use to get your objects
public static class Config
{
    public static Func<IDbConnection> GetConnection =
      DefaultConfig.GetConnection;

     public static Func<IDbCommand> GetCommand =
      DefaultConfig.GetCommand;
}

//Default implementations of the config functions
public static class DefaultConfig
{

  //Configure a connection
  public static IDbConnection GetConnection()
  {
       return new SqlConnection("myconnstr");
  }

  //Configure a command
  public static IDbCommand GetCommand()
  {
      IDbCommand cmd = new SqlCommand();

      //Inject connection into command
      //Any sort of injection is possible here, ctor, prop, method etc.
      cmd.Connection = Config.GetConnection();

      return cmd;
  }
}

Look at the “Config” class above, it exposes “Func of IDbConnection”, meaning it will return a delegate that in turn returns a DbConnection once invoked.
This allows me to assign new implementations to that static field if I want to, and thus make all consumers of that delegate get objects according to my new implementation.

My code can then consume the factory like this:


IDbCommand cmd = Config.GetCommand();

That looks quite OK, doesn’t it?

And in order to change the implementation for some resolve method:


Config.GetCommand = () => new MySpecialCommand();

Or if you like the old delegate syntax:


Config.GetCommand = delegate
                    {
                        return new MySpecialCommand();
                    };

I use this all the time now, I simply change the config implementation for my unit tests and use the default implementation when running the real applications.

//Roger

Written by Roger Alsing

May 7, 2009 at 7:50 pm

Posted in .NET, C#