Archive

Archive for the ‘Castle Project’ Category

Dependency Injection Inversion

January 19th, 2010 stiiifff No comments

Seems there is still a lot of confusion about what is Inversion of Control, what is Dependency Injection, what are the differences between the two, and how to apply one or the other properly.

Several people have reacted to a controversial post by Uncle Bob on that topic with, among the most vocal ones, Davy. ;-)

IMHO, some of the best posts on the subject that really make a clear distinction between IoC & DI are the following ones:

The whole point of IoC (forget a minute about DI) is to break the dependencies between your classes and design them as  loosely-coupled as possible (to the point that it’s actually useful of course, it’s not an engineering contest).

All the benefits that you get:

  • Dependency Injection
  • Better testability
  • Better maintainability

are just consequences of the good design of your classes (read about SOLID also).

In the end, it’s just good Object-Oriented design, nothing more. And by good, it doesn’t mean complex, it’s actually quite simple once you got it.

Categories: Castle Project, MEF Tags: , ,

Stepping onto the Bus

October 12th, 2009 stiiifff No comments

I recently had the chance to follow the Advanced Distributed Systems Design with SOA course with Udi Dahan in Brussels, a rejuvenating experience for various reasons : I had no real-world SOA or Messaging Bus experience, it helped me clear out some misunderstandings I had about DDD and also, although painful at first, Udi finger pointed all the bad habits & misconceptions I had accumulated over the years (I can still hear him squeaking “Northwind ! Northwind !“).

So here I am, entering the realm of SOA, EDA & DDD that might well be heaven on earth for both business people & software-makers, the place we all heard of but never saw. But let’s start slowly, and discover my first endeavor with NServiceBus, shall we? :)

For a good introduction on NServiceBus, I suggest you to read the post from Jan who has been doing research on the same aforementioned topics as well.

This post will focus on how well NServiceBus, NHibernate, FluentNHibernate & Castle Framework play together and how to make them fly in a DDD context. Ok, ok, enough talking, show me the code man !!! :D

To manage my NHibernate sessions (ISession), I like to use the Castle’s NHibernate Integration facility, as it gives me a nice abstraction in the form of the ISessionManager component:

ISessionManager

Next to that, a little more than a month ago, the 1.0 version of FluentNHibernate was released, and it’s really neat for both NHibernate configuration & mappings. So, I like to use it as well:

Fluently.Configure(config)
  .Database(MsSqlConfiguration.MsSql2008
    .DefaultSchema("dbo")
    .ConnectionString(c => c
      .FromConnectionStringWithKey("Northwind"))
    .QuerySubstitutions("true 1, false 0")
    .DoNot.UseOuterJoin()
    .ShowSql())
  .Mappings(m => m
    .FluentMappings.AddFromAssemblyOf<CatalogMap>()
    .ExportTo(System.Environment.CurrentDirectory))
  .BuildConfiguration();

One very nice thing about NServiceBus (and its Generic Host) is that it acknowledges from the start that our softwares have to operate in different environments and for that, it offers a very clean solution : Profiles.

Wrapping it all up, wouldn’t it be nice if I could use Castle’s NHibernate Integration facility for useful components like ISessionManager (and others, more on that later), FluentNHibernate for configuration & mappings and take advantage of NServiceBus Profiles ? Hell yeah !!! Well, that’s actually quite easy & clean. :)

First, configure the NH facility in your config file:

<castle>
  <facilities>
    <facility id="nhibernate.facility" type="Castle.Facilities.NHibernateIntegration.NHibernateFacility, Castle.Facilities.NHibernateIntegration">
      <factory id="nhibernate.factory"/>
    </facility>
  </facilities>
</castle>

Notice that the configuration for the factory is empty … indeed, we want to configure it fluently in the code.

Create a Profile Handler class (implements a IHandleProfile role interface) which simply registers an object into the container (NSB is container-agnostic) :

public class IntegrationProfileHandler : IHandleProfile<Integration>
{
  public void ProfileActivated()
  {
    Configure.Instance.Configurer
      .RegisterSingleton<IConfigurationContributor>(
        new IntegrationNHibernateConfig());
  }
}

… and finally, an implementation of the IConfigurationContributor interface … which is part of Castle’s NHibernate Integration facility, and will be called before NH’s SessionFactory is built in order to, well, contribute to the configuration. :)

public class IntegrationNHibernateConfig : IConfigurationContributor
{
  public void Process(string name, Configuration config)
  {
    Fluently.Configure(config)
      .Database(MsSqlConfiguration.MsSql2008
        .DefaultSchema("dbo")
        .ConnectionString(c => c
          .FromConnectionStringWithKey("Northwind"))
        .QuerySubstitutions("true 1, false 0")
        .DoNot.UseOuterJoin()
        .ShowSql())
      .Mappings(m => m
        .FluentMappings.AddFromAssemblyOf<CatalogMap>()
        .ExportTo(System.Environment.CurrentDirectory))
      .BuildConfiguration();
  }
}

Ok, very nice … but I’m not done yet.

A nice concept that we want to use when querying in a true DDD fashion is the notion of Fetching Strategy (read more about it here & there). We need Fetching Strategies for a very simple reason:

Make sure that once we call into the Domain Model to perform a certain action, it has everything it needs to do its job, without causing lazy-loading to trigger and possibly N+1 select problems.

For that matter, I define a simple interface IFetchingStrategy (IEntityRole is just a marker interface):

public interface IFetchingStrategy<TEntityRole>
    where TEntityRole : IEntityRole
{
  string[] FetchList { get; }
}

… that I can then implement to define a fetching strategy per entity role:

public interface IRegisterProductInCatalog : IEntityRole
{
  void RegisterProduct(string category,
         string productName, string productDescription);
}

public class RegisterProductInCatalogStrategy : IFetchingStrategy<IRegisterProductInCatalog>
{
  public string[] FetchList
  {
    get { return new[] { "Categories.Products" }; }
  }
}

Now, it would be nice if I could get an easy access to those fetching strategies … well, that’s what you use an IoC container for ;) Here is the configuration of Castle’s Windsor container in NServiceBus endpoint’s configuration class:

public class EndpointConfig : IConfigureThisEndpoint, AsA_Server, IWantCustomInitialization
{
  public void Init()
  {
    var container = new WindsorContainer(new XmlInterpreter());

    Configure.With()
      .CastleWindsorBuilder(container)
      .XmlSerializer();

    container.Register(
      AllTypes
        .Of(typeof(IFetchingStrategy<>))
        .Pick(Configure.TypesToScan)
        .WithService.FirstInterface()
    );
  }
}

Fluent configuration for the Bus & the Container ! Woohoo, my head is turning ! :D

Now, for the final part, the MessageHandler that makes use of all those cuties & with the help some little extension methods:

public class ProductManager : IHandleMessages<RegisterProductInCatalogRequest>
{
  public virtual IBus Bus { get; set; }
  public virtual ISessionManager SessionManager { get; set; }
  public virtual IFetchingStrategy<IRegisterProductInCatalog> Strategy { get; set; }

  public virtual void Handle(RegisterProductInCatalogRequest message)
  {
    using (var session = SessionManager.OpenSession())
    {
      var catalog =
            session.For<Catalog>(message.CatalogId)
                   .Apply(Strategy)
                   .UniqueResult<IRegisterProductInCatalog>();

      catalog.RegisterProduct(message.CategoryName,
                              message.ProductName,
                              message.ProductDescription);
    }
  }
}

I don’t know you, but that’s the kind of code that makes me happy (like a hippo). :)

Comments, feedback, suggestions are all welcome ! ;)

Castle DynamicProxy Tutorial

July 2nd, 2009 stiiifff No comments

A while ago, Krzysztof Koźmic started a blog post series about Castle Project’s DynamicProxy (DP2).

If you wanna know what the heck are:

  • Proxies with & without target
  • Interceptors
  • Interceptor selectors

Go read his amazing tutorial. I’m sure you’ll learn something ;)

If needed, have  a quick refresh on AOP : here, there & there.

And if you get inspired by DP2 and the Castle Project in general, follow the evolution & suggest new ideas !

Dependencies, ownership & lifetime

October 23rd, 2008 stiiifff No comments

A quick post to link Hammett's (creator of Castle Project, Windsor IoC container, and now PM on the MEF project) very interesting article about Dependencies, ownership & lifetime of components.

Domain-Driven Design with Linq & ORM – Part 2

June 19th, 2008 stiiifff 2 comments

In my last post about DDD & Linq (1.5 month ago … oops), I showed the following piece of code:

ServiceLocator.Register<IUnitOfWorkFactory, NHibernateUnitOfWorkFactory>();

using (UnitOfWork.Start())
{
    ITransaction tx = UnitOfWork.Current.BeginTransaction(IsolationLevel.ReadCommitted);
    try
    {
        IRepository<Customer> cr = UnitOfWork.Current.GetRepository<Customer>();
        Customer customer = cr.FindOne(c => c.Id == "AROUT");
        customer.Address = "125 Hanover Sq.";
        cr.Save(customer);
        tx.Commit();
    }
    catch
    {
        if (tx != null) tx.Rollback();
    }
    finally
    {
        if (tx != null) tx.Dispose();
    }
}

After thinking about it, refactoring it 10 times, I sat down this morning and finally got it the way I wanted (don’t ask me why it took so long lol):

// Configure your favorite IoC container:
// - Register an IUnitOfWorkFactory
// - Register an IRepositoryFactory
// - Register a generic IRepository<TEntity>
//   (your container must support open generic types).
// - Configure your container to use the IRepositoryFactory
//   to create instances of the IRepository<TEntity> component
//   (your container must support factories).
// Once your IoC container is set up, configure it as the ServiceProvider
// (must implement the IServiceProvider interface or use a wrapper) for the ServiceLocator helper
ServiceLocator.ServiceProvider = container;

// Start a unit of work
using (IUnitOfWork uow = UnitOfWork.Start())
{
    // Get an instance of repository
    IRepository<Customer> cr = ServiceLocator.GetService<IRepository<Customer>>();

    // Retrieve data with a Linq query
    Customer customer = cr.FindOne(c => c.CustomerID == "AROUT");

    // Modify retrieved entity
    customer.Address = "000 Hanover Sq.";

    // Ask repository to save changes
    cr.Save(customer);

    // Mark the unit of work as complete to propagate changes to data source
    uow.Complete();
}

The re-worked IRepository<T> looks like this:

public interface IRepository<TEntity> : IDisposable where TEntity : class
{
    long Count();
    long Count(Expression<Func<TEntity, bool>> predicate);
    void Add(TEntity entity);
    void Add(IEnumerable<TEntity> entities);
    void Remove(TEntity entity);
    void Remove(IEnumerable<TEntity> entities);
    void RemoveAll();
    void RemoveAll(Expression<Func<TEntity, bool>> predicate);
    void Save(TEntity entity);
    void Save(IEnumerable<TEntity> entities);
    TEntity FindOne(Expression<Func<TEntity, bool>> predicate);
    IEnumerable<TEntity> FindAll();
    IEnumerable<TEntity> FindAll(Expression<Func<TEntity, bool>> predicate);
    IQueryable<TEntity> QueryAll();
    IQueryable<TEntity> QueryAll(Expression<Func<TEntity, bool>> predicate);
}

I think it looks better ;) I currently have UoW & Repository factories for the following ORM:

  • NHibernate
  • ActiveRecord
  • LinqToSql
  • EntityFramework

The code is still very experimental, relies a lot of Castle Project’s libraries (some might view it as a pro, others a con …), and I unfortunately don’t have much time to work more on it. If there is any interest for it, I might drop it online in its current state (basic samples, no unit test, code analysis spitting out a lot of warnings).

Feedback is welcomed. :)

Possible Improvements:

  • For simplification purpose, I might remove the dependency to a ‘ServiceProvider‘ and instead define a simple ‘UnitOfWork.Configure‘ method where we can specify the type of the IUnitOfWorkFactory & IRepositoryFactory.
  • Should the IUnitOfWork interface expose a ‘GetRepository<TEntity>‘ method to get rid of the ugly static call to ‘ServiceLocator.GetService<IRepository<T>>‘ ?

CircuitBreaker Interceptor

June 12th, 2008 stiiifff 1 comment

An interesting pattern discussed in Release It!, Design and Deploy Production-Ready Software, is the CircuitBreaker pattern. I was thinking about implementing it in C# but well, as often, someone took care of it already (thus less work for me). :)

Tim Ross has a first post on his blog where he describes the CircuitBreaker and his implementation. In the second part, he introduces several improvements such as a ServiceLevel variable and the possibility to ignore certain exception types.

Although a very nice implementation, I wasn't thinking about a class for my CircuitBreaker implementation … but about an Interceptor.

Indeed, when designing a system built of loosely-coupled components using an IoC container, you will often add interceptors at strategic places (integration points with external systems) to catch failures, log statistics, … So, it makes sense to make the CircuitBreaker an interceptor that can be applied to those critical parts of your application in order to fail-fast in the event of repeated failures & relieve the external system that is under stress.

Here a quick implementation of Tim's class as an interceptor (using Castle Windsor IoC container) … the test code is dumb, but I guess you'll get the point. ;)

CircuitBreakerInterceptor.rar

Note: Instead of porting the whole code into the Interceptor class, it's also possible to simply get a CircuitBreaker object injected by he container into the Interceptor (interceptors are just a special kind of components), and the Interceptor would delegate the invocation call to the CircuitBreaker.

Btw, for those who don’t know Castle Windsor container well yet (never too late to learn something), this small sample also demonstrate the ease of using & configuring the container (as well as creating interceptors).

ActiveRecord & Repository pattern

May 19th, 2008 stiiifff 1 comment

Hammett has a post where he, among others, advises:

I don’t encourage people to use AR with the AR base class. Use the
ARMediator and use the repository pattern or a dao pattern to increase
isolation and testability.

Yes ! It seems not many people knew it (I did, I'm a Reflector addict lol) but you can use ActiveRecord without base classes for your entities (ActiveRecordBase), just use the [ActiveRecord] attribute.

That way, you get:

  • Attribute-based mapping declaration (instead of manual edition of NHibernate mapping files, which can be cumbersome).
  • Well-tested plumbing code like session & transaction scopes.
  • Easy querying through ActiveRecordMediator static methods, instead of direct use of NHibernate ISession.

Now, if you want the best ORM experience in a DDD-context:

  • Use the Repository pattern, to get an additional layer of abstraction between your application code & your particular ORM.
  • Use Linq queries in your repositories, for rich ORM-independent querying capabilities (your ORM has to support Linq of course).

I've been refactoring & cleaning up some code lately, I will soon drop the first draft of Yoot.DomainDriven, a non-intrusive framework for pragmatic Domain-Driven Design with nice abstraction of Units of work & Linq-friendly repositories, and implementations for mainstream ORM tools. :)

Domain-Driven Design with Linq & ORM

May 1st, 2008 stiiifff 2 comments

We all now that an ORM plays an important role in a DDD architecture … but it would be nice if we could write our Domain Model without being tightly coupled to our favorite ORM tool, especially the code we write in Repositories. Thanks to Linq, we already have a way to abstract our queries (our ORM 'just has to' support Linq, anyway that's a requirement for a good ORM nowadays). The other thing we should be able to abstract is the object, specific to each ORM, that is the interface with the persistence layer, that keeps track of the changes on entities, the 'context' or the 'session' object.

Well, most ORM tools are implementing similar Patterns, namely UnitOfWork, IdentityMap, LazyLoad … so it is fair to assume that it should be possible to build an abstract layer that would allow us to work at a higher level, and have providers for our favorite ORM tools.

Here is a sample from some early code I wrote:

ServiceLocator.Register<IUnitOfWorkFactory, NHibernateUnitOfWorkFactory>();

using (UnitOfWork.Start())
{
    ITransaction tx = UnitOfWork.Current.BeginTransaction(IsolationLevel.ReadCommitted);
    try
    {
        IRepository<Customer> cr = UnitOfWork.Current.GetRepository<Customer>();
        Customer customer = cr.FindOne(c => c.Id == "AROUT");
        customer.Address = "125 Hanover Sq.";
        cr.Save(customer);
        tx.Commit();
    }
    catch
    {
        if (tx != null) tx.Rollback();
    }
    finally
    {
        if (tx != null) tx.Dispose();
    }
}

The Repository interface, which makes heavy use of Linq to express query criterions, looks like this:

public interface IRepository<TEntity> where TEntity : class
{
    long Count();
    long Count(Expression<Func<TEntity, bool>> predicate);
    void Delete(TEntity entity);
    void Delete(IEnumerable<TEntity> entities);
    void DeleteAll();
    void DeleteAll(Expression<Func<TEntity, bool>> predicate);
    void Save(TEntity entity);
    void Save(IEnumerable<TEntity> entities);
    TEntity FindOne(Expression<Func<TEntity, bool>> predicate);
    IEnumerable<TEntity> FindAll();
    IEnumerable<TEntity> FindAll(Expression<Func<TEntity, bool>> predicate);
    IQueryable<TEntity> ProjectAll();
    IQueryable<TEntity> ProjectAll(Expression<Func<TEntity, bool>> expression);
}

Wanna use LinqToSql or EntityFramework instead of NHibernate … well, that’s easy, just change the first line to:

ServiceLocator.Register<IUnitOfWorkFactory, LinqToSqlUnitOfWorkFactory>();

or

ServiceLocator.Register<IUnitOfWorkFactory, EntityFrameworkUnitOfWorkFactory>();

Nice isn’t it ? ;)
We can also have:

ServiceLocator.Register<IUnitOfWorkFactory, ActiveRecordUnitOfWorkFactory>();

or

ServiceLocator.Register<IUnitOfWorkFactory, EussUnitOfWorkFactory>();

Well, I think you get the point.
So, what you think ? Suggestions & remarks are welcome.

“Not invented here” disclaimer: This code is largely inspired and based on code from Castle Project & Rhino.Commons. I just generalized it.

“Pre-Pre-Pre-Pre-Pre Alpha code” disclaimer: This code is quite experimental, it is not (yet) fully unit-tested and doesn’t support (yet) all the capabilities of the different ORM tools presented here.

Dependency Injection on your WCF & WF services

April 28th, 2008 stiiifff No comments

You are using an Inversion of Control container for your application components and you are exposing some services through WCF. Wouldn’t it be nice if you could host those services in your container and benefit from Dependency Injection ?

Well, that’s easy if you’re using Castle Project’s Windsor container: just register the WcfIntegration facility and you’re on track:

  • Public properties or Constructor arguments will automatically be injected by the container.
  • Any component registered in the container that implements the IServiceBehavior or IOperationBehavior interfaces will be easily applicable to your WCF services.

Similarly, there is also a Workflow Foundation integration facility that provides the following functionalities:

  • Host the WorkflowRuntime engine in the container, making it available for any workflow-aware components.
  • Automatically add to the WorkflowRuntime any Workflow services (components inherited from WorkflowRuntimeService base class) or External Data exchange services (components with ExternalDataExchange attribute).

Hope one finds that interesting … :)

DSL News

April 21st, 2008 stiiifff No comments

For those who are interested in Domain-Specific Languages (anybody reading this blog except myself?), there are a couple of interesting news this week:

As a side note, the feature I’m eagerly awaiting in the next version of the DSL Tools is the DSL extensibility one. Imagine being able to extend your base DSL model using plugins, whether it be classes, properties, rules, validations … this opens up a whole new world.

For one of my current project in which I need basic extensibility, I tried to mix the System.Plugin framework with the DSL Tools … I stopped during the process, too complex, too heavy, and used a simpler Provider architecture instead. For more advanced scenarii, I’ll wait for the new model provided by Visual Studio codename “Rosario“.

Categories: Castle Project, DSL, WCF, WPF Tags: , , ,