Override Unity Mappings in Configuration File

Topics: Enterprise Library Core, General discussion
Jun 8, 2010 at 3:25 PM

Hi,

I have a unit test project with a configuration that contains several Unity registrations like follows.

<unity>
    <container>
      <register type="IAlpha" mapTo="Alpha" />
    </container>
</unity>

Is there a way in code to temporarily override the mapping from IAlpha to Alpha with something like IAlpha to MockAlpha?  I want to temporarily divert calls to IAlpha to a mock class for the duration of a unit test then restore the original mapping.  I tried calling the IUnityContainer.RegisterType method at the beginning of the test, but unfortunately the invocation of the method still goes to Alpha instead of MockAlpha.  e.g. something like this didn't work since the invocations of IAlpha still went to Alpha instead of MockAlpha

IUnityContainer unityContainerInstance = new UnityContainer();
unityContainerInstance.LoadConfiguration();
unityContainerInstance.RegisterType(typeof(IAlpha), typeof(MockAlpha), new ContainerControlledLifetimeManager());
//Execute test
....
unityContainerInstance.Resolve<IAlpha>().SomeMethod();

Disclaimer:  There may be slight syntactic errors in my examples since they aren't copy and pastes.

Any help is appreciated.

Thanks,

Jason

Jun 9, 2010 at 12:34 AM

In Unity, the last one which gets registered just overwrites the previous.  The code you posted should work.  Are you sure you did the exact same thing in your project? 

BTW, please post Unity questions in the Unity forum.

 

Sarah Urmeneta
Global Technology and Solutions
Avanade, Inc.
entlib.support@avanade.com

Jun 9, 2010 at 7:35 PM

You are right, the new register overrides the previous register in the configuration file.   It was indeed working in my code, but there was a bug in my code where the order of operations was such that this change was not properly detected.  i.e. I had a lingering reference to the object resolved before the register change so it was not updated when the new register occurred.

Thanks!