You don’t mess with Unity’s policies

Recently I ran into a problem. Quite well designed system degraded in terms of performance after a few commits. The whole architecture is wired with an infrastructure library written with unity container as a base for dependency injection. One of its features is a simple adding proxies, for instance adding some information to an exception’s data in case of throwing one. The interceptor doing it is quite simple:

public class ExceptionDataAppendingInterceptor : IInterceptor
{
	public void Intercept(IInvocation invocation)
	{
		try
		{
			invocation.Proceed();
		}
		catch (Exception ex)
		{
			ex.AppendMethodCallData(
			    invocation.Method, invocation.Arguments);
			throw;
		}
	}
}

The exension method appending data is a bit more complex but does not add any value to the post.

Having in mind that exception can be thrown at various points of an application and having it run for the very first time in the test environment, I configured unity to set proxy to the majority of created objects, which are resolved as interfaces (proxifing their interfaces).
When I run a profiled, it showed a major overhead created by one strategy, being responsible for wrapping a created object with use of DynamicProxy2. What the profiler shown was plenty of calls to IEnumerable extensions method. The strategy called one policy which before fixing looked like this:

public class InterceptorSelectorPolicy : IBuilderPolicy
{
	private readonly IDictionary<Type, List<Func<IBuilderContext, IInterceptor>>> 
		_activators;
	private static readonly ProxyGenerator ProxyGenerator = new ProxyGenerator();

	public InterceptorSelectorPolicy(
		IDictionary<Type, List<Func<IBuilderContext, IInterceptor>>> activators)
	{
		_activators = activators;
	}

	/// <summary>
	/// Determines whether the specified context is applicable for proxy generation.
	/// </summary>
	public bool IsApplicable(IBuilderContext context)
	{
		return _activators.ContainsKey(BuildKey.GetType(context.OriginalBuildKey));
	}

	/// <summary>
	/// Creates the proxy using <see cref="IBuilderContext.Existing"/> as target
	/// and <see cref="IBuilderContext.OriginalBuildKey"/> as proxied interface type.
	/// </summary>
	public object CreateProxy(IBuilderContext context)
	{
		var typeToProxy = BuildKey.GetType(context.OriginalBuildKey);

		return ProxyGenerator.CreateInterfaceProxyWithTarget(
			typeToProxy,
			context.Existing,
			_activators[typeToProxy]
			.Select(a => a(context))
			.ToArray());
	}
}

It’s worth to mentioned that it was called every time an object was created… After refactorization the code lost all the enumerable _create_state_machine_for_my_iterator_ stuff and was changed to:

public class InterceptorSelectorPolicy : IBuilderPolicy
{
	private readonly Type _typeToProxy;
	private readonly Func<IBuilderContext, IInterceptor>[] _activators;
	private static readonly ProxyGenerator ProxyGenerator = new ProxyGenerator();

	public InterceptorSelectorPolicy(Type typeToProxy, 
		Func<IBuilderContext, IInterceptor>[] activators)
	{
		_typeToProxy = typeToProxy;
		_activators = activators;
	}

	/// <summary>
	/// Gets a value indicating whether this proxified should be applied.
	/// </summary>
	/// <value>
	///     <c>True</c> if this instance is applicable; otherwise, <c>false</c>.
	/// </value>
	public bool IsApplicable
	{
		get { return _activators != null && _activators.Length > 0; }
	}

	/// <summary>
	/// Creates the proxy using <see cref="IBuilderContext.Existing"/> as target
	/// and <see cref="IBuilderContext.OriginalBuildKey"/> as proxied interface type.
	/// </summary>
	/// <param name="context">The context.</param>
	/// <returns>Returns created proxy.</returns>
	public object CreateProxy(IBuilderContext context)
	{
		return ProxyGenerator.CreateInterfaceProxyWithTarget(
			_typeToProxy,
			context.Existing,
			CreateInterceptors(context));
	}

	private IInterceptor[] CreateInterceptors(IBuilderContext context)
	{
		var result = new IInterceptor[_activators.Length];
		for (var i = 0; i < _activators.Length; i++)
		{
			result[i] = _activators[i](context);
		}
		return result;
	}
}

No dictionary look ups, no iterators, no needed overhead. The whole idea was simplified and now, for an object having no need of proxifing it is reduced to a simple, nolock _is_null_ array check called by a post build strategy. You don’t mess with Unity’s policies unless you have a nice stress test written.

Recent tasks

I’ve read a few articles about documenting a project in a way that make it more usable for non-authors. As I published Themis’ first version, there was a need of providing some documentation and that was the thing which occupied me recently. There still are a few pages which should be written and I hope I’ll do it during a next week. I encourage you to visit Themis’ page and write sth if any part of documentation is to complex or to fuzzy.

The other thing which I did was writing a patch for SolrNet. Unfortunately for me, the project is hosted on GitHub which causes a delay of submitting the patch – I’ve got to learn GIT! :F

NHibernating with interfaces as entities, pt. 2

The solution to the question, what can go wrong with NHibernate, when you use interfaces as your entities mapped with NH is… naming.

When you try to save a transient object, to make it persistent with NH, you call ISession.Save(object) method. If you drilled down its implementation you’d see that it fires NH’s event SaveOrUpdateEvent which finally, after calling the default event handler for this event, would try to get the persister of the entity being saved. What for? Because you’ve got to know how you are trying to make persistent and later, saved in a db.

Let’s take a look at the implementation provided with a SessionImpl.GetEntityPersister method. At the very first lines of code, the method calls another session’s method called GuessEntityName. Guessing method firstly delegates the question to the interceptor, and if one was kind enough to help it to deal with it, it returns the result of the interceptor’s call. Otherwise… GetType of the entity method is called! If the result of resolving entity’s interface from container was wrapped with a proxy, some proxy type will be returned (in DynamicProxy it will be nicely placed in a dynamic assebly with a cute namespace) and because it is not what was mapped, an error will occur!

The only solution is to traverse all interfaces implemented by the object and find the one you’ve written in your mappings in the interceptor method. You can do it simply with the code presented below, initializing the finder with all interfaces of all your entities. Remember to do not cross trees in a forest of your interface-entity derivations:P

/// <summary>
/// The interface finder allows you to find the deepest interface from a specified set of interfaces.
/// </summary>
/// <remarks>
/// The interfaces inheritance graph should be a forest.
/// </remarks>
public class InterfaceFinder : IDisposable
{
	private readonly List<Type> _interfaces;
	private readonly Dictionary<Type, int> _interfaceToLevel;
	private readonly Dictionary<Type, Type> _cacheObjectTypeToInterface;
	private readonly ReaderWriterLockSlim _rwl;

	public InterfaceFinder(IEnumerable<Type> interfaces)
	{
		if (!interfaces.Any())
		{
			throw new ArgumentException("No interfaces passed", "interfaces");
		}

		_interfaces = interfaces.ToList();
		_interfaceToLevel = new Dictionary<Type, int>();
		_cacheObjectTypeToInterface = new Dictionary<Type, Type>();

		// prepare dictionary counting ancestors
		foreach (var i in interfaces)
		{
			if (!i.IsInterface)
			{
				throw new ArgumentException(string.Format("The type {0} is not an interface", i.FullName));
			}

			var ancestorCount = i.GetInterfaces().Count(t => interfaces.Contains(t));
			_interfaceToLevel[i] = ancestorCount;
		}

		// create only when fully initialized
		_rwl = new ReaderWriterLockSlim();
	}

	/// <summary>
	/// Gets the depest interface from inheritance trees retrieved from
	/// the constructor parameter.
	/// </summary>
	/// <param name="o">The object to be searched for interfaces.</param>
	/// <returns>The deepest interface of a hierachy found in the object interfaces.</returns>
	public Type GetDeepestInterface(object o)
	{
		o.ThrowIfNull("o");

		var type = o.GetType();

		// enter read lock, try found, multiple threads can enter
		_rwl.EnterReadLock();
		try
		{
			Type result;
			if (_cacheObjectTypeToInterface.TryGetValue(type, out result))
			{
				return result;
			}
		}
		finally
		{
			_rwl.ExitReadLock();
		}

		// write lock, cause no entry found, one thread can enter
		_rwl.EnterWriteLock();
		try
		{
			Type result;
			if (_cacheObjectTypeToInterface.TryGetValue(type, out result))
			{
				return result;
			}

			result = GetDeepestInterface(type);
			_cacheObjectTypeToInterface[type] = result;
			return result;
		}
		finally
		{
			_rwl.ExitWriteLock();
		}
	}

	private Type GetDeepestInterface(Type objType)
	{
		var interfaces = objType.GetInterfaces().Intersect(_interfaces);

		var levels = interfaces.Select(t => _interfaceToLevel[t]).ToArray();
		var countDistinct = levels.Distinct().Count();

		if (countDistinct != levels.Length)
		{
			throw new InvalidOperationException(
				"The type of passed object implements to many interfaces, " +
			"disallowing to find one path in derivation tree. The found implemented interfaces are: " +
			string.Join(", ", interfaces.Select(i => i.FullName).ToArray()));
		}

		// find the interface with the biggest depth
		return interfaces.OrderByDescending(t => _interfaceToLevel[t]).First();
	}

	public void Dispose()
	{
		_rwl.Dispose();
	}
}

Tests not included :P