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>();

About erictummers

My work as a recruited developer changes almost every month. 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 Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s