TypeInitializationException when using types from TPL library

We are using one of the DataFlow blocks (BufferBlock<T> in System.Threading.Tasks.Dataflow) from a library that our service uses, and since adding that type, we have been getting the following exception in our base AppHost:

[NullReferenceException: Object reference not set to an instance of an object.]
   Gene.Services.AppHosts.AppHostBase..cctor() in c:\Projects\github\mindkin\gene\src\Services.AppHosts.Common\AppHostBase.cs:13

[TypeInitializationException: The type initializer for &#39;Gene.Services.AppHosts.AppHostBase&#39; threw an exception.]
   Gene.Services.AppHosts.AppHostBase..ctor(String serviceName, Assembly[] assembliesWithServices) in c:\Projects\github\mindkin\gene\src\Services.AppHosts.Common\AppHostBase.cs:37
   Crib.Services.AppHostBase..ctor() in c:\Projects\github\mindkin\crib\src\Services\AppHost.gen.cs:45
   Crib.Services.AppHost..ctor() +43
   Crib.Services.Global.Application_Start(Object sender, EventArgs e) in c:\Projects\github\mindkin\crib\src\Services\Global.asax.cs:24

[HttpException (0x80004005): The type initializer for &#39;Gene.Services.AppHosts.AppHostBase&#39; threw an exception.]
   System.Web.HttpApplicationFactory.EnsureAppStartCalledForIntegratedMode(HttpContext context, HttpApplication app) +544
   System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(IntPtr appContext, HttpContext context, MethodInfo[] handlers) +186
   System.Web.HttpApplication.InitSpecial(HttpApplicationState state, MethodInfo[] handlers, IntPtr appContext, HttpContext context) +172
   System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(IntPtr appContext, HttpContext context) +402
   System.Web.Hosting.PipelineRuntime.InitializeApplication(IntPtr appContext) +343

[HttpException (0x80004005): The type initializer for &#39;Gene.Services.AppHosts.AppHostBase&#39; threw an exception.]
   System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +579
   System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +112
   System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +716

The offending line of code simply calls the ctor of ServiceStack.AppHostBase with our list of discovery assemblies (containing our services and DTO’s), as it always has.

Since we added code that uses BufferBlock<T> to one of our other libraries (not in the list of discovery assemblies), but added the TPL nuget to the service project, we get this exception. (Service project directly references the library assembly and the System.Threading.Tasks.Dataflow Assembly)

Does anyone know why we would get this exception now?

p.s. I stress, if we comment out the use of the BufferBlock<T> type in our library, everything works fine again. This is not a setup problem of our service that we have seen yet.

I have no guess as to why you’re getting that Exception but that StackTrace looks weird, are you using a Custom build of ServiceStack? Or at least a custom AppHostBase? If you are, can’t you just debug to see what’s causing the NRE?

Note: TypeInitializationException usually points to a static initialization problem, e.g. In a static constructor or the initialization of a static field.

If you can’t find it, I’d need a small, stand-alone repro to be able to debug what the issue is, which you can submit to: https://github.com/ServiceStack/Issues

V.56 build of servicestack from nuget.org. Nothing special there.

The Crib/AppHost.gen.cs is the AppHost of the service. Yes, we have a base class which is the Gene/AppHostBase.cs in the stack trace. The Gene/AppHostBase.cs derives directly from ServiceStack.AppHostBase.

We do nothing in that ctor except pass the ServiceName and discoveryAssemblies to ServiceStack.AppHostBase.

The only thing that is static and being initialized in Gene/AppHostBase.cs is the following code:

internal static HostConfig HostConfig = new HostConfig
        {
            HandlerFactoryPath = ApiPath,
            MapExceptionToStatusCode =
            {
                { typeof(ValidationError), 400 },
                { typeof(ArgumentException), 400 },
                { typeof(ArgumentNullException), 400 },
                { typeof(ArgumentOutOfRangeException), 400 },
                { typeof(RuleViolationException), 400 },
                { typeof(AuthenticationException), 401 },
                { typeof(UnauthorizedAccessException), 401 },
                { typeof(ForbiddenException), 403 },
                { typeof(ResourceNotFoundException), 404 },
                { typeof(RoleViolationException), 404 },
                { typeof(MethodNotAllowedException), 405 },
                { typeof(ResourceConflictException), 409 },
            },
        };

Which has not at all changed.

We call appHost.SetConfig(AppHostBase.HostConfig); with that static in the Configure() method of the service.

Could the exception be coming from the initialization of the HostConfig??
Those exception types are in an assembly that references the assembly that has uses the System.Threading.Tasks.Dataflow.BufferBlock<T>

Yeah possibly, collection initializers requires MapExceptionToStatusCode to be a non-null collection, try changing it to:

MapExceptionToStatusCode = new Dictionary<Type, int>
{
    { typeof(ValidationError), 400 },
    { typeof(ArgumentException), 400 },
    { typeof(ArgumentNullException), 400 },
    { typeof(ArgumentOutOfRangeException), 400 },
    { typeof(RuleViolationException), 400 },
    { typeof(AuthenticationException), 401 },
    { typeof(UnauthorizedAccessException), 401 },
    { typeof(ForbiddenException), 403 },
    { typeof(ResourceNotFoundException), 404 },
    { typeof(RoleViolationException), 404 },
    { typeof(MethodNotAllowedException), 405 },
    { typeof(ResourceConflictException), 409 },
},

Thx, I’ll give that a nudge, and let you know.

Good grief! that seems to have fixed it (just declaring the collection as new Dictionary<Type, int>.
Thanks @mythz for picking that up.

p.s. I still can’t see why it would fix it? all those types are still loaded fine!
What am I missing here? I feel stoopid now! I don’t get why would that fix it?

Trying to populate any collection with a collection initializer that’s null will throw a NRE. You have to be careful how static types are initialized as they’re not always predictable so it’s better to be explicit and defensive when initializing static types.