Monday, April 15, 2013

XAML Resource Loading

Visual Studio 2012 kept locking my .DLLs. It happened mostly after starting a debugger session. I could trace back the problem to a GetManifestResourceStream() call.

Solution

This is my solution that seems to be working:

public Stream GetResourceStreamByType(Type type, string resourceName)
{
  var location = Assembly.GetAssembly(type).Location;
  var assemblyBytes = File.ReadAllBytes(location);

  var appDomain = AppDomain.CreateDomain("Resource domain");
  var assembly = appDomain.Load(assemblyBytes);

  return assembly.GetManifestResourceStream(resourceName);
}

public BitmapImage GetBitmapByType(Type type, string resourceName)
{
  var bmp = new BitmapImage();
  using (var source = GetResourceStreamByType(type, resourceName))
  {
    bmp.BeginInit();
    bmp.StreamSource = source;
    bmp.EndInit();
  }

  return bmp;
}

Reasons

Loading the resource by calling the GetManifestResourceStream() on the current assembly loads the assembly into the debugger's app domain which is Visual Studio in this case. Reading the bytes and loading them manually prevents this behavior.

I couldn't reload the form again after loading the resources this way so I had to create a separate app domain as well. Without separate app domain the assembly was already loaded and the reloading didn't happen with an error message like 'does not have a resource identified by the URI'.