Tag Archive for 'autofac' Page 2 of 4



Know thy dependencies and control them efficiently

Nick has upgraded the MVC extension of Autofac to support the latest drop of ASP.NET MVC.

Unfortunately, this broke the integration server, since (as deduced from looking at the license) we can not redistribute the MVC binaries in the trunk\Resources\MVC folder, as it is with other build dependencies.

Fixing that was a trivial thing - install the latest and drop the assemblies into the cache. However, that was still some manual operation that could’ve been avoided.

In any proper and efficient development environment Don’t Repeat Yourself (DRY) principle is not limited by the code, it goes beyond and makes everything related to the project delivery more efficient (where appropriate and efficient).

We can’t do this in this situation due to the legal restriction. And every user trying to build autofac extension from the sources will have to repeat these actions of mine - find the proper redistributable, download it, install and make sure the assemblies are in the GAC.

Now, how efficient is that?

In any big project one could have more of this small and repetitive operations that stack up to take away your time, distract you or cause problems. This could be a bottleneck in critical situations.

Here’s simple efficiency test for you: “How much time would it take you to release your solution on a fresh development machine?”

Current xLim implementation has approx 36. projects and 11 external dependencies, but requires only install of .NET SDK 3.5 and DXperience 7.3.5 to release and configure it (Web UI, Desktop Smart Client, Server, Automation engine and tools) from the sources (and TortoiseSVN to get the sources). These two can be downloaded from the web storage (it is better even to have dedicated ftp to store them in one place as well).

Given that, hot fix becomes “no-problem” even if you are far away from the office and only have notebook with Windows XP, Internet connection and one hour.

Update: there are more details on this atomic solution structure in: Organization of xLim solutions: development, svn and integration

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…

How to avoid tight IoC coupling in non-deterministic resolution scenarios?

Normally IoC should never go into the code below the level of module/component registration. That’s the rule.

But what if some specific component needs to resolve components based on some conditions (i.e. resolving by name when name is passed externally)?

You can use dictionary if the components are singletons, but this would not work if they have to be resolved in the current scope. For example, we might need to execute some workflow class knowing only its name and interface. And some workflow class (neither we know, nor do we care) could just need to access the data store within the scope of the current session.

These simple interface declarations help me to manage scenarios like this with a couple of lines of code, while keeping the IoC intrusion minimal:

public interface IResolver<Param, Object>
{
  Object Resolve(Param param);
}

public interface IResolver<Object> : IResolver<string, Object> { }

Additionally there is a simple class to lend IoC to the components with inlining:

public class Resolver<Param, Object> : IResolver<Param, Object>
{
  private readonly Func<Param, Object> _function;

  public Resolver(Func<Param, Object> function)
  {
    _function = function;
  }

  public Object Resolve(Param param)
  {
    return _function(param);
  }
}

public sealed class Resolver<Object> :
  Resolver<string, Object>, IResolver<Object>
{
  public Resolver(Func<string, Object> function) : base(function)
  {
  }
}

With that you can register named resolution of some interface (ICommand, for example) with this nice statement:

builder.Register(scope => new Resolver<ICommand>(
  name => scope.ResolveByName<ICommand>(name)))
  .As<IResolver<ICommand>>()
  .WithScope(InstanceScope.Container);

and then it could be later used in any component like

public sealed class TaskExecutor
{
  private readonly Resolver<ICommand> _commands;
  public TaskExecutor(Resolver<ICommand> commands)
  {
    _commands = commands;
  }

  ...
  _commands.Resolve(commandName).Execute();
  ...
}

Remarks:

  • The resolution interfaces should always be explicitly written. That’s just to keep the code under control.
  • This function-based resolver interface simplifies unit testing quite a bit (especially if you use MockContainer).
  • Do not try this code at home with your IoC container unless this container is Autofac.
  • Using some global static class (i.e.: IoC.ResolveByName…) is not a valid solution either, because:
    • That’s global static class and its usage just complicates code management and testing
    • Static resolution would not have any clue about the current scope (rendering it useless)

Why do not we resolve delegates in IoC?

Do you see the difference between these two declarations of some imaginary command?

public sealed class DeleteCommand : ICommand
{
  private readonly IRecordSelector _recordSelector;
  private readonly IMessageBoxService _messaging;
  private readonly IRecordManager _recordManager;

  public DeleteCommand(IRecordSelector recordSelector,
    IMessageBoxService messaging, IRecordManager recordManager)
  {
    _recordSelector = recordSelector;
    _messaging = messaging;
    _recordManager = recordManager;
  }

  public void Execute()
  {
    List<XPObject> records;
    if (_recordSelector.TryGetOneOrMoreRecords(out records))
    {
      if (_messaging.Ask("Do you really want to delete '{0}' records?",
        records.Count))
      {
        _recordManager.Remove(records);
        _recordSelector.RefreshData();
      }
    }
  }
}

and this one

Action<IRecordSelector, IMessageBoxService, IRecordManager> command =
  (selector, messaging, manager) =>
{
  List<XPObject> records;
  if (selector.TryGetOneOrMoreRecords(out records))
  {
    if (messaging.Ask("Do you really want to delete '{0}' records?",
      records.Count))
    {
      manager.Remove(records);
      selector.RefreshData();
    }
  }
};

Class version is longer but it can be resolved in IoC. The delegate is more concise but it does not resolve.

So, why do not we resolve delegates in IoCs?

PS: additional difference is that if command is stateless then it could be resolved only once in the IoC scope and the subsequent executions will use “cached” version (Container scope instead of Factory could be used). But I’d trade that for the DRY principle.