Tag Archive for 'IoC'

What is common between Autofac, Castle and MEF?

Ok, now it is official. The father of Autofac .NET IoC Container, Nicholas Blumhardt, has joined the team of Krzysztof Cwalina at Microsoft.

He will be the Program Manager in a team that’s building the Managed Extensibility Framework

Additionally Hamilton Verissimo (founder of the Castle project) will be joining the same team.

Congratulations and good luck, Nick! You can make the difference out there))

PS: Nick and Hamilton will still be able to spend as much time as they want on their pet projects. There’s the permission from Microsoft for that.

Implementing ORM-independent Linq queries

We’ll get back from the Boo + Business + DSL to the XPO + ORM + IOC series for a little bit.

Nicholas Blumhardt has just written an interesting and extremely thorough article on Implementing the Specification Pattern via Linq. Let’s try to play with the idea and take it a one step down the road. Here we can:

1. Add ORM abstraction by implementing generic IRepository (of T) interface:

public interface IRepository<T>
{
	IQueryable<T> Find(QueryFor<T> query);
	IQueryable<T> Find(string criteria);
	IQueryable<T> Find<K>() where K : QueryFor<T>, new();
	IQueryable<T> Query();

	// ...
}

Continue reading ‘Implementing ORM-independent Linq queries’

What do you do when the IoC container grows big?

Nicholas Blumhardt has just released version 1.1 of his wonderful Autofac IoC container. The details are available at autofac community forum. You can download both .NET 2.0 version and .NET 3.5 version. Note, that .NET 3.5 version is much more powerful because of extension methods and lambda expressions.

And after this milestone there’s some logical transformation of the project on the way.

Autofac users have expressed their concerns of the core IoC growing too heavy because of all the extensions and integrations being developed. Additionally, there’s always some tendency for the core to be tweaked in order to accomplish something with some extensions.

I believe that’s what has happened with the Castle project. It got heavy.

Nick has agreed to isolate the core from the non-BCL integrations and extras and move them to a separate autofac-contrib project. This separate project will have the same continuous integration support and openness to the contributions.

Additionally there is some consideration to streamline and solidify the framework experience around autofac-contrib while keeping up with the principles of efficient development and D.R.Y.

Think of solution structure that has been designed with the framework extensibility in mind. For example, with the ability to get single integration library by just firing of the build script with the required switches. Something like:

go net2 –D:include=”nmock2,nhibernate,startable,coreutils” integrate distrib

Another opportunity being considered is to design integrations/extras with the replace-ability in mind (so that, for example, it would be much easier to replace one ORM with another, while keeping the interfaces the same).

What do you think?

How to implement unit-testable abstraction and reusable domain models with IoC + ORM?

In the previous post in ORM+IoC series we’ve managed to decouple away from the ORM-based collection and the literal-based syntax (which was bound to the logics of eXpress Persistent Objects ORM).

In this post we’ll try to get rid of all the remaining coupling (while making it unit-testable) and even add domain-based extensibility that is easy to implement.

Let’s modify the code:

public sealed class DisableAllAccounts : ICommand
{
  private readonly IOrderedQueryable<IAccount> _accounts;
  private readonly ILog _log;

  public DisableAllAccounts(IOrderedQueryable<IAccount> accounts, ILog log)
  {
    _accounts = accounts;
    _log = log;
  }

  public void Execute()
  {
    _log.Write("Disabling accounts:");

    var accounts = from c in _accounts
                   where (c.Disabled == false)
                   select c;

    foreach (var account in accounts)
    {
      IComment comment = account.CreateComment();
      comment.Text = string.Format("Account {0} was disabled on {1}",
        account.FirstName, DateTime.Now);
      comment.Save();
      account.Disabled = true;
      account.Save();
    }
  }
}

Continue reading ‘How to implement unit-testable abstraction and reusable domain models with IoC + ORM?’

How to use ORM (XPO), IoC, C# 3.5 syntax, Linq and .NET 2.0 together?

One of the most important features of any proper development architecture, environment or process, is that the synergy (network) effects accumulate, if you keep doing the right things. IoC/DI, unit testing and TDD, continuous integration - all these just form up the external side of how everything works. They simply help (or force) to shape the logics of the development to make everything fold smoothly and let your solutions accumulate the benefits.

Now, let us get back to the IoC+ORM series and take one more look at the ICommand implementation from the last post. It could be improved quite a bit:

public sealed class DisableAllAccounts : ICommand
{
  private readonly IRepository<Account> _accounts;
  private readonly ILog _log;

  public DisableAllAccounts(IRepository<Account> accounts, ILog log)
  {
    _accounts = accounts;
    _log = log;
  }

  public void Execute()
  {
    _log.Write("Disabling accounts:");
    _accounts.CriteriaString = "Disabled=0";
    foreach (var account in _accounts)
    {
      _log.Write(account.Name);
      account.Disabled = true;
      account.Save();
    }
  }
}

Things become better as we throw out things that do not fit well. So let us remove our custom IRepository<> from this picture (along with the FireCollection behind it) and get rid of the string literal in favor of something that is compiler-checked

Continue reading ‘How to use ORM (XPO), IoC, C# 3.5 syntax, Linq and .NET 2.0 together?’

How to inject ORM with some IoC?

This post continues ORM+IoC series, namely - the discussion initiated by “How to decouple your code from ORM (XPO) while granting it the power to IoC?” and comments that followed.

Let us try to inject ORM itself with some IoC and see what happens. Take a look at the following exaggerated command example:

public sealed class CreateRandomAccount : ICommand
{
  private readonly Account _account;
  private readonly ILog _log;

  public CreateRandomAccount(Account account, ILog log)
  {
    _account = account;
    _log = log;
  }

  public void Execute()
  {
    _log.Write("Creating new random account");
    _account.Name = Guid.NewGuid().ToString();
    _account.Disabled = true;
    _account.Save();
  }
}

I like to use some ICommand implementations as examples since they help to crystallize the effects of IoC in one single piece.

The code above, being resolved in some container, just does what it says: it asks for the class (registered as Factory instance) and saves it to some repository. IoC uses Session from the current scope to create the instance and so it will use UoW, session in transaction or whatever session descendant is available in the container. Additionally it writes a note to the logger.

Continue reading ‘How to inject ORM with some IoC?’

How to decouple your code from ORM (XPO) while granting it the power to IoC?

It is Sunday and there is too much work to do, but Nicholas Blumhardt has just got me totally distracted with his latest post on Enabling Rich Domain Models with Services. Comments by Jeremy Gray have just added to that.

So, it seems that in addition to ruling the IoC coupling out of the component code (while keeping its resolution powers in) we can simply rule out the entire ORM out of the code as well (in my case DevExpress eXpress Persistent Objects go for the ORM, but there is no big difference).

Take a look at the code below:

public sealed class ApproveTask : ICommand
{
  private readonly Session _session;

  public ApproveTask(Session session)
  {
    _session = session;
  }

  public void Execute()
  {
    var entries = new XPCollection<AccountEntry>(_session,
      CriteriaOperator.Parse("Approved=0"));
    foreach (var entry in entries)
    {
      entry.Approved = true;
    }
    _session.Save(entries);
  }
}

The code has some strong coupling with the XPO ORM, does not it? Now, what if we were to rewrite it like this:

public sealed class ApproveTask : ICommand
{
  private readonly IRepositoryFactory<IAccount> _repository;

  public ApproveTask(IRepositoryFactory<IAccount> repository)
  {
    _repository = repository;
  }

  public void Execute()
  {
    var filtered = _repository.GetFiltered("Approved=0");
    foreach(var account in filtered)
    {
      account.Approved = true;
    }
    _repository.Save(filtered);
  }
}

Now that feels to be much better in terms of re-usability and testability.

To implement that we just need to:

  1. Decouple our business objects from the ORM via the interfaces (if they are strongly coupled like it is done in XPO, where they have to inherit from the base class)
  2. write a generic IRepositoryFactory implementation for the XPO ORM that simply creates the wrapper for the XPCollection or XPServerCollection
  3. register the factory with the container scope to make it operate in the context of the Session or UnitOfWork of the current scope

Bonuses:

  • I use the string-based criteria in these code examples, but chances are that it would be possible to write server-side Linq statements instead.
  • Since the IRepository is the “IoC front” code, we can hand it the powers to IoC as well. For example, the domain objects might want to have that ILog interface or some IHashProvider. We can pass these down to the repositoryFactory same way it has been done with the IResolver: use “Action<T> injectProperties” that gets called after the domain object is retrieved by ORM (these will still have the current Session/Transation since they are resolved in the current scope). Additionally, since the IRepository implements “T Create()” member, we can present components with new objects that are already DI’d with the container.

But it gets more complicated if some business object holds a collection of aggregated objects as well…