Search code examples
c#unity-containerapp-configioc-containerunity2.0

How can I extend a Unity catalog at runtime?


I want to map most of my interfaces to concrete classes in my app.config file. However, I would like to register some interfaces to the same Unity catalog at runtime. I tried the code below, but it gives me a SynchronizationLockException: Object synchronization method was called from an unsynchronized block of code.

IUnityContainer container = new UnityContainer();

UnityConfigurationSection configSection =
    (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
configSection.Containers.Default.Configure(container);

container.RegisterInstance<IInterface>(new ConcreteObject());

How can I register an object at runtime in a Unity catalog initialized from app.config?

I am using the Unity version (2.0) that ships with Prism4.


Solution

  • This is a common problem, but not technically an error, with registering unity objects. Change your regsitration to this:

    container.RegisterType<IInterface, ConcreteObject>(new ContainerControlledLifetimeManager());
    

    That should fix your problem.

    That exception gets thrown because of this:

    Can Unity be made to not throw SynchronizationLockException all the time?