For a long time, I had a very annoying error message when I called the IsRegistered method on the Unity container.
Error Message:
System.ArgumentException: GenericArguments[0], 'T', on 'Infrastructure.Data.NHibernateRepository`1[T]' violates the constraint of t
ype 'T'. ---> System.TypeLoadException: GenericArguments[0], 'T', on 'Infrastructure.Data.NHibernateRepository`1[T]' violates the c
onstraint of type parameter 'T'.
Last week I finally found the root cause of this issue. Let’s have a look at my code first:
public interface IRepository<T> where T:Entity
{
}
public class NHibernateRepository<T> : IRepository<T> where T : Entity, new()
{
}
So what’s causing the issue? Have a look at the generic constraints. You see that my interface is less restrictive than my implementation and that is what makes Unity chokes...
One workaround(which is still far from ideal) is that you can apply the same type constraints to the interface. Another (better) workaround is posted by Walter Almeida. Either way I hope it will be solved in the next release of Unity…