MEF configuration and parallel transactions

aspnetWhile testing my ASP.NET Web API solution single requests are fine, but multiple requests give HTTP500 after a long wait.

A MEF configuration setting caused parallel transactions and the database provider was unable to handle them.

Setup

ASP.NET Web API offers an extension to use your own IoC. I’m using the MEF implementation from stackoverflow. Below the configuration code with my Handler and Context added.

var registration = new RegistrationBuilder();
registration.ForTypesDerivedFrom<Controller>()
            .SetCreationPolicy(CreationPolicy.NonShared)
            .Export();
registration.ForTypesDerivedFrom<ApiController>()
            .SetCreationPolicy(CreationPolicy.NonShared)
            .Export();
registration.ForTypesDerivedFrom<IHandler>()
            .Export<IHandler>();
registration.ForTypesDerivedFrom<IContext>()
            .Export<IContext>();
var catalog = new ApplicationCatalog(registration);
var container = new CompositionContainer(catalog, true);

Exception

Using Fiddler I’m sending multiple requests to the Web API. The result is HTTP500 An error occurred while starting a transaction on the provider connection. See the inner exception for details. with the inner exception on the server SqlConnection does not support parallel transactions.

Solution

The Handler and Context object are shared between the two requests. While creating a record for the first request the second request starts a transaction for creating it’s record. Setting the CreationPolicy for both objects to NonShared solved it.

registration.ForTypesDerivedFrom<IHandler>()
            .SetCreationPolicy(CreationPolicy.NonShared)
            .Export<IHandler>();
registration.ForTypesDerivedFrom<IContext>()
            .SetCreationPolicy(CreationPolicy.NonShared)
            .Export<IContext>();
Unknown's avatar

About erictummers

Working in a DevOps team is the best thing that happened to me. I like challenges and sharing the solutions with others. On my blog I’ll mostly post about my work, but expect an occasional home project, productivity tip and tooling review.
This entry was posted in Development and tagged , , . Bookmark the permalink.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.