Search code examples
c#inversion-of-controlunity-containerunity2.0

Using Unity, how do I resolve a name value to a static class property?


I have a project which has multiple Resource (resx) files along with the accompanying .designer.cs generated files. Each of these classes has a public static property of type System.Resources.ResourceManager.

What I can't seem to figure out is how to get the configuration right for unity so that I can resolve it and execute. Obviously, the code below will not work - since it will not let me register the object that way.

public static string GetStringValue(name, tokenName)
{ 
   using (IUnityContainer container = new UnityContainer())
   {
        container.LoadConfiguration("ResourceManagers");
        var resolvedManager = container.Resolve<ResourceManager>(name);
        return resolvedManager.GetString(tokenName);
   }
}

And given the following configuration...

<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
    <assembly name="Web" />
    <container name="ResourceManagers">
      <register name="Manager1" mapTo="Web.Manager1Strings.ResourceManager" type="System.Resources.ResourceManager" />
    </container>
  </unity>

here is the designer code - this is generated by codedom.

public class Manager1Strings 
{
    ...
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        public static global::System.Resources.ResourceManager ResourceManager {
            get {
                if (object.ReferenceEquals(resourceMan, null)) {
                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Web.Resources.Manager1.Manager1Strings", typeof(Manager1Strings).Assembly);
                    resourceMan = temp;
                }
                return resourceMan;
            }
        }
    ...
}

Solution

  • Okay I was able to resolve this issue but it was only because I had control over the generation of the designer files (CodeDom).

    In summary:

    1. I created an interface which had 1 method "GetString"
    2. I tweaked the CodeDom logic (similar to this) to implement the interface.
    3. I was then able to resolve instances of the interface via unity