Autofac couldn't resolve dependency on TeamCity

386 views Asked by At

I have a such code (It's a part of unit tests executed by nunit-console):

class MyClass
{
    [DI(Type = typeof(MyClass))]
    public IMyClass MyClassProperty {get;set;}
}

By reflection i'm scanning such classes and then register in Autofac:

// Register MyClass as IMyClass
autofacBuilder.RegisterType(diAttribute.Type).As(propertyInfo.PropertyType);

After that i need to resolve this property in the same way - by reflection:

autofacContainer.Resolve(propertyInfo.PropertyType) // it contains IMyClass

When I'm launching this code locally it works well. But doesn't work on TeamCity. Fails with error:

Error: 'Autofac.Core.DependencyResolutionException: An exception was thrown while executing a resolve operation. See the InnerException for details. ---> Common Language Runtime detected an invalid program. (See inner exception for details.) ---> System.InvalidProgramException: Common Language Runtime detected an invalid program.
1

There are 1 answers

1
Travis Illig On

There are a lot of questions on StackOverflow about this exception. It's not an Autofac problem, it's a JIT compiler problem. A quick Google search on the exception yields a lot of info.

You even see projects like NewtonSoft.Json running into the issue.

The exception itself means "a program contains invalid Microsoft intermediate language (MSIL) or metadata; generally this indicates a bug in the compiler that generated the program."

Microsoft has a KB article on troubleshooting the issue. Whenever folks have resolved it, as far as I've seen, it's always one of two fixes:

  • A change to the compilation options. For example, some people running encryption/obfuscation sorts of tools find turning them off helps; others find turning off compiler optimization fixes it. (The KB article has some tips.)
  • Making sure things are patched to the latest versions. I've run into other similar situations myself where things work great on my machine but not on the build server; or vice versa. Almost invariably it's because I have my machine all patched up but the build server has been languishing unpatched; or someone just patched up the build server and I haven't installed my patches yet.

I'd recommend starting with the patches since that's usually the simplest fix. Use Windows Update to make sure both you and the build server have the latest .NET updates. If that doesn't fix it, check out some of the troubleshooting tips in the articles and questions above.