Wednesday, November 30, 2011

Unity IsRegistered throws exceptions when registering Open Generic types.

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…


Anonymous said...

Arrrgh. So that's what it was. An hour of my life down the drain. Thanks very much for this.

Priya Kannan said...

Great post!I am actually getting ready to across this information,i am very happy to this commands.Also great blog here with all of the valuable information you have.Well done,its a great knowledge. Python Training in Chennai