Search code examples
c#.netinversion-of-controlunity-container

Unity 5.8: registration by convention "Inheritance security rules violated"


I have updated Unity 4 container to Unity 5.8 but I have problem with registration by convention in this version. It completly doesn't work. Fresh project, installed following packages:

Install-Package Unity.Container -v 5.8.7
Install-Package Unity.RegistrationByConvention -v 2.1.7

super simple code:

class Program
{
    static void Main(string[] args)
    {
        UnityContainer uc = new UnityContainer();

        uc.RegisterTypes(AllClasses.FromLoadedAssemblies(), (c) => WithMappings.FromMatchingInterface(c));
    }
}

and it gives exception

System.TypeLoadException: „Inheritance security rules violated while overriding member: 
Unity.RegistrationByConvention.Exceptions.DuplicateTypeMappingException.GetObjectData(System.Runtime.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext)'. Security accessibility of the overriding method must match the security accessibility of the method being overriden.

I have no idea what is wrong, it used to work in previous version. Does any know how to use registration by convenion in new Unity?


Solution

  • Looking at this answer, this seems to be a problem with Unity.RegistrationByConvention. Their DuplicateTypeMappingException should have the SecurityCriticalAttribute on GetObjectData which is indeed present in System.Exception as stated in the exception you posted.

    Meanwhile, I think it should suffice to only register your own types, not just everything from every library in the project.