Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 899715
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 15, 20262026-05-15T15:15:57+00:00 2026-05-15T15:15:57+00:00

The Unity dependency injection container has what seems to be a widely known issue

  • 0

The Unity dependency injection container has what seems to be a widely known issue where the SynchronizedLifetimeManager will often cause the Monitor.Exit method to throw a SynchronizationLockException which is then caught and ignored. This is a problem for me because I like to debug with Visual Studio set to break on any thrown exception, so every time my application starts up I’m breaking on this exception multiple times for no reason.

How can I prevent this exception from being thrown?

Wherever this issues is mentioned elsewhere on the web, the advice usually involves changing the debugger settings to ignore it. This is akin to going to the doctor and saying, “Doctor, Doctor, my arm hurts when I raise it,” to be told, “Well, stop raising it.” I’m looking for a solution that stops the exception being thrown in the first place.

The exception occurs in the SetValue method because it makes the assumption that GetValue will have been called first, where Monitor.Enter is called. However, the LifetimeStrategy and UnityDefaultBehaviorExtension classes both regularly call SetValue without calling GetValue.

I’d rather not have to change the source code and maintain my own version of Unity, so I’m hoping for a solution where I can add some combination of extensions, policies, or strategies to the container that will ensure that, if the lifetime manager is a SynchronizedLifetimeManager, GetValue is always called before anything else.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-15T15:15:58+00:00Added an answer on May 15, 2026 at 3:15 pm

    I’m sure there’s a lot of ways code could call SynchronizedLifetimeManager, or a descendant like ContainerControlledLifetimeManager, but there were two scenarios in particular that were causing me problems.

    The first was my own fault – I was using constructor injection to supply a reference to the container, and in that constructor I was also adding the new instance of the class to the container for future use. This backwards approach had the effect of changing the lifetime manager from Transient to ContainerControlled so that the object Unity called GetValue on was not the same object it called SetValue on. The lesson learned is don’t do anything during build-up that could change an object’s lifetime manager.

    The second scenario was that every time RegisterInstance is called, UnityDefaultBehaviorExtension calls SetValue without calling GetValue first. Luckily, Unity is extensible enough that, with enough bloody-mindedness, you can work around the problem.

    Start with a new behavior extension like this:

    /// <summary>
    /// Replaces <see cref="UnityDefaultBehaviorExtension"/> to eliminate 
    /// <see cref="SynchronizationLockException"/> exceptions that would otherwise occur
    /// when using <c>RegisterInstance</c>.
    /// </summary>
    public class UnitySafeBehaviorExtension : UnityDefaultBehaviorExtension
    {
        /// <summary>
        /// Adds this extension's behavior to the container.
        /// </summary>
        protected override void Initialize()
        {
            Context.RegisteringInstance += PreRegisteringInstance;
    
            base.Initialize();
        }
    
        /// <summary>
        /// Handles the <see cref="ExtensionContext.RegisteringInstance"/> event by
        /// ensuring that, if the lifetime manager is a 
        /// <see cref="SynchronizedLifetimeManager"/> that its 
        /// <see cref="SynchronizedLifetimeManager.GetValue"/> method has been called.
        /// </summary>
        /// <param name="sender">The object responsible for raising the event.</param>
        /// <param name="e">A <see cref="RegisterInstanceEventArgs"/> containing the
        /// event's data.</param>
        private void PreRegisteringInstance(object sender, RegisterInstanceEventArgs e)
        {
            if (e.LifetimeManager is SynchronizedLifetimeManager)
            {
                e.LifetimeManager.GetValue();
            }
        }
    }
    

    Then you need a way to replace the default behavior. Unity doesn’t have a method to remove a specific extension, so you have to remove everything and put the other extensions back in again:

    public static IUnityContainer InstallCoreExtensions(this IUnityContainer container)
    {
        container.RemoveAllExtensions();
        container.AddExtension(new UnityClearBuildPlanStrategies());
        container.AddExtension(new UnitySafeBehaviorExtension());
    
    #pragma warning disable 612,618 // Marked as obsolete, but Unity still uses it internally.
        container.AddExtension(new InjectedMembers());
    #pragma warning restore 612,618
    
        container.AddExtension(new UnityDefaultStrategiesExtension());
    
        return container;
    }
    

    Notice that UnityClearBuildPlanStrategies? RemoveAllExtensions clears out all of the container’s internal lists of policies and strategies except for one, so I had to use another extension to avoid inserting duplicates when I restored the default extensions:

    /// <summary>
    /// Implements a <see cref="UnityContainerExtension"/> that clears the list of 
    /// build plan strategies held by the container.
    /// </summary>
    public class UnityClearBuildPlanStrategies : UnityContainerExtension
    {
        protected override void Initialize()
        {
            Context.BuildPlanStrategies.Clear();
        }
    }
    

    Now you can safely use RegisterInstance without fear of being driven to the brink of madness. Just to be sure, here’s some tests:

    [TestClass]
    public class UnitySafeBehaviorExtensionTests : ITest
    {
        private IUnityContainer Container;
        private List<Exception> FirstChanceExceptions;
    
        [TestInitialize]
        public void TestInitialize()
        {
            Container = new UnityContainer();
            FirstChanceExceptions = new List<Exception>();
            AppDomain.CurrentDomain.FirstChanceException += FirstChanceExceptionRaised;
        }
    
        [TestCleanup]
        public void TestCleanup()
        {
            AppDomain.CurrentDomain.FirstChanceException -= FirstChanceExceptionRaised;
        }
    
        private void FirstChanceExceptionRaised(object sender, FirstChanceExceptionEventArgs e)
        {
            FirstChanceExceptions.Add(e.Exception);
        }
    
        /// <summary>
        /// Tests that the default behavior of <c>UnityContainer</c> leads to a <c>SynchronizationLockException</c>
        /// being throw on <c>RegisterInstance</c>.
        /// </summary>
        [TestMethod]
        public void UnityDefaultBehaviorRaisesExceptionOnRegisterInstance()
        {
            Container.RegisterInstance<ITest>(this);
    
            Assert.AreEqual(1, FirstChanceExceptions.Count);
            Assert.IsInstanceOfType(FirstChanceExceptions[0], typeof(SynchronizationLockException));
        }
    
        /// <summary>
        /// Tests that <c>UnitySafeBehaviorExtension</c> protects against <c>SynchronizationLockException</c>s being
        /// thrown during calls to <c>RegisterInstance</c>.
        /// </summary>
        [TestMethod]
        public void SafeBehaviorPreventsExceptionOnRegisterInstance()
        {
            Container.RemoveAllExtensions();
            Container.AddExtension(new UnitySafeBehaviorExtension());
            Container.AddExtension(new InjectedMembers());
            Container.AddExtension(new UnityDefaultStrategiesExtension());
    
            Container.RegisterInstance<ITest>(this);
    
            Assert.AreEqual(0, FirstChanceExceptions.Count);
        }
    }
    
    public interface ITest { }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Our project is using constructor-based Dependency Injection (we're using Unity as our container) and
I am thinking about using Microsoft Unity for my Dependency Injection tool in our
In an ASP.NET MVC application when using a custom Dependency Injection container (in this
After all what I have read about Dependency Injection and IoC I have decided
I am finally getting my feet wet with Dependency Injection (long overdue); I got
I'm currently just starting to implement Dependency injection so I can start testing my
I am having a problem using the Unity Application Block, I have created a
I am pretty new to the Unity Application Block and am a little stuck
I'm working on my 1st project using MS Unity IoC framework. If I have
What's pros and cons of using Enterprise Library Unity vs other IoC containers (Windsor,

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.