AppDomain and Shadow Copy


.Net Framework has a feature called Shadow Copy. When shadow copy is enabled on an appdomain, assemblies loaded in that appdomain will be copied to a shadow copy cache directory, and will be used from there. This is great because the original file is not locked. So it can be changed at will. ASP.NET uses this extensively. Actually, shadow copy is enabled on every appdomain created by ASP.NET.


 


This feature is implemented by fusion.


 


Unfortunately the documentation for shadow copy is rather poor. MSDN has documentation on various things affecting shadow copy. But it does not discuss the detail of shadow copy feature. This post is an attempt to discuss in detail how shadow copy works.


 


All the discussion is based on AppDomainSetup class unless specified.


 


There are three things affecting shadow copy:



  1. How to enable shadow copy?

  2. What will be shadow copied?

  3. Where do shadow copied bits go? 

1. How to enable shadow copy?


MSDN says it all. Set AppDomainSetup.ShadowCopyFiles to true will enable shadow copy.


 


2. What will be shadow copied?


AppDomainSetup.ShadowCopyDirectories controls what will be shadow copied. It is a list of directory names, separated by a semicolon. Each directory name should be absolute directory path. Assemblies loaded from those directories will be shadow copied. If ShadowCopyDirectories is null, all assemblies will be shadow copied. (An interesting corner case is what if ShadowCopyDirectories is empty string. I’ll leave this as an exercise for the readers. What do you think the behavior will be?)


 


3. Where do shadow copied bits go?


AppDomainSetup.CachePath + AppDomainSetup.ApplicationName control where shadow copied bits go. If both CachePath and ApplicationName are set, shadow copied bits will go to CachePath\ApplicationName. Otherwise shadow copied bits will go to your download cache (which is stored in %userprofile%\local settings\application data\assembly). The combination of CachePath and ApplicationName is really handy for ASP.NET, because they can set a common CachePath, and have each application shadow copy to a different location.


You are responsible to clean up the shadow copy cache if you set CachePath+ApplicationName. In the case of download cache as shadow copy cache, it is automatically managed by fusion.


 


On the default appdomain you cannot change its AppDomainSetup. But you can use AppDomain’s API to change the properties. The relevant APIs are:


SetCachePath, SetShadowCopyFiles, SetShadowCopyPath (the name of this one is not consistent with AppDomainSetup.ShadowCopyDirectories). The ApplicationName is set to the name of the application on default domain.  

Comments (15)

  1. David Levine says:

    Thanks for the info, keep it coming. On the empty string question, I’d guess that nothing would be copied since it would not locate a directory whose name was an empty string.

    A question about the shadow copy directories; you state that each directory must be specified as an absolute path. This implies that assemblies will be shadow copied regardless of their original location on the machine, or will this only affect files from subdirectories at or below the appbase? If it’s from anywhere then does this mean that assemblies loaded using LoadFrom or LoadFile as opposed to Load will also be shadow copied? In other words, does the fusion load context have an effect on assemblies that are shadow copied? Thanks.

    Dave

  2. Junfeng says:

    David,

    Regarding the exercise, yes, you are correct. Nothing will be copied.

    You are correct about the LoadFrom also. Shadow copy will be applied to both Assembly.Load and Assembly.LoadFrom. What we check is that this assembly is from one of those directories. If they are, we shadow copy it.

    But Assembly.LoadFile does not benefit from shadow copy. Because LoadFile does not go throught fusion. Fusion only handles Assembly.Load(string) and Assembly.LoadFrom.

  3. Denis sent a comment using the contact link. Please use the comment to post question. Other people may be interested in the answer.

    Shadow Copy in AppDomain is not the same as Volume Shadow Copy feature in Windows Server 2003. We don’t keep track of history. It is mainly a workaround to not lock the original file.

    Sender: Denis AUGER

    Email: auger_denis@emc.com

    =====================================

    Hi,

    I have found in the API how to active a Volume Shadow Copy with appDomain class.

    But I need, through the API, to get all the "previous versions" giving a file name.

    I also need to launch a restore of a file or a directory.

    Do you know how is it possible through the API ?

    Thank’s very much for your help

    Denis

  4. chornbe says:

    You must also encapsulate the loaded assembly into another class, which is loaded by the new appdomain. Here’s the code as it’s working for me: (I’ve created a few custom exception types, and you’ll notice I had them back – they’re not descended from MarshalByRefObject so I can’t just throw them from the encapsulated code)

    — cut first class file

    using System;

    using System.Reflection;

    using System.Collections;

    namespace Loader{

    /* contains assembly loader objects, stored in a hash

    * and keyed on the .dll file they represent. Each assembly loader

    * object can be referenced by the original name/path and is used to

    * load objects, returned as type Object. It is up to the calling class

    * to cast the object to the necessary type for consumption.

    * External interfaces are highly recommended!!

    * */

    public class ObjectLoader : IDisposable {

    // essentially creates a parallel-hash pair setup

    // one appDomain per loader

    protected Hashtable domains = new Hashtable();

    // one loader per assembly DLL

    protected Hashtable loaders = new Hashtable();

    public ObjectLoader() {/*…*/}

    public object GetObject( string dllName, string typeName, object[] constructorParms ){

    Loader.AssemblyLoader al = null;

    object o = null;

    try{

    al = (Loader.AssemblyLoader)loaders[ dllName ];

    } catch (Exception){}

    if( al == null ){

    AppDomainSetup setup = new AppDomainSetup();

    setup.ShadowCopyFiles = "true";

    AppDomain domain = AppDomain.CreateDomain( dllName, null, setup );

    domains.Add( dllName, domain );

    object[] parms = { dllName };

    // object[] parms = null;

    BindingFlags bindings = BindingFlags.CreateInstance | BindingFlags.Instance | BindingFlags.Public;

    try{

    al = (Loader.AssemblyLoader)domain.CreateInstanceFromAndUnwrap(

    "Loader.dll", "Loader.AssemblyLoader", true, bindings, null, parms, null, null, null

    );

    } catch (Exception){

    throw new AssemblyLoadFailureException();

    }

    if( al != null ){

    if( !loaders.ContainsKey( dllName ) ){

    loaders.Add( dllName, al );

    } else {

    throw new AssemblyAlreadyLoadedException();

    }

    } else {

    throw new AssemblyNotLoadedException();

    }

    }

    if( al != null ){

    o = al.GetObject( typeName, constructorParms );

    if( o != null && o is AssemblyNotLoadedException ){

    throw new AssemblyNotLoadedException();

    }

    if( o == null || o is ObjectLoadFailureException ){

    string msg = "Object could not be loaded. Check that type name " + typeName +

    " and constructor parameters are correct. Ensure that type name " + typeName +

    " exists in the assembly " + dllName + ".";

    throw new ObjectLoadFailureException( msg );

    }

    }

    return o;

    }

    public void Unload( string dllName ){

    if( domains.ContainsKey( dllName ) ){

    AppDomain domain = (AppDomain)domains[ dllName ];

    AppDomain.Unload( domain );

    domains.Remove( dllName );

    }

    }

    ~ObjectLoader(){

    dispose( false );

    }

    public void Dispose(){

    dispose( true );

    }

    private void dispose( bool disposing ){

    if( disposing ){

    loaders.Clear();

    foreach( object o in domains.Keys ){

    string dllName = o.ToString();

    Unload( dllName );

    }

    domains.Clear();

    }

    }

    }

    }

    — end cut

    — cut second class file

    using System;

    using System.Reflection;

    namespace Loader {

    // container for assembly and exposes a GetObject function

    // to create a late-bound object for casting by the consumer

    // this class is meant to be contained in a separate appDomain

    // controlled by ObjectLoader class to allow for proper encapsulation

    // which enables proper shadow-copying functionality.

    internal class AssemblyLoader : MarshalByRefObject, IDisposable {

    #region class-level declarations

    private Assembly a = null;

    #endregion

    #region constructors and destructors

    public AssemblyLoader( string fullPath ){

    if( a == null ){

    a = Assembly.LoadFrom( fullPath );

    }

    }

    ~AssemblyLoader(){

    dispose( false );

    }

    public void Dispose(){

    dispose( true );

    }

    private void dispose( bool disposing ){

    if( disposing ){

    a = null;

    System.GC.Collect();

    System.GC.WaitForPendingFinalizers();

    System.GC.Collect( 0 );

    }

    }

    #endregion

    #region public functionality

    public object GetObject( string typename, object[] ctorParms ){

    BindingFlags flags = BindingFlags.CreateInstance | BindingFlags.Instance | BindingFlags.Public;

    object o = null;

    if( a != null ){

    try{

    o = a.CreateInstance( typename, true, flags, null, ctorParms, null, null );

    } catch (Exception){

    o = new ObjectLoadFailureException();

    }

    } else {

    o = new AssemblyNotLoadedException();

    }

    return o;

    }

    public object GetObject( string typename ){

    return GetObject( typename, null );

    }

    #endregion

    }

    }

    — end cut

  5. andrei says:

    I have the following problem:

    I followed the steps described here, as well as anywhere i looked for documentation regarding this issue and the result is not quite what I expected. I obtain a shadow copy of my dll, but both files, the original and the shadow copied dll are locked by the process.

    here is a piece of the code, please tell me what is wrong with it:

    System.AppDomainSetup appDomainSetup = new AppDomainSetup();

    appDomainSetup.ShadowCopyDirectories = "D:\pathToMyApp\bin\Debug";

    appDomainSetup.ShadowCopyFiles = "true";

    appDomainSetup.CachePath = @"D:\pathToMyApp\bin\Debug";

    appDomainSetup.ApplicationName = "appName";

    System.AppDomain appDomain = System.AppDomain.CreateDomain("Domain" + "someName",

    new System.Security.Policy.Evidence(AppDomain.CurrentDomain.Evidence),

    appDomainSetup);

    System.Reflection.AssemblyName assemblyName = System.Reflection.AssemblyName.GetAssemblyName("pathToTheDll");

    System.Reflection.Assembly assembly = appDomain.Load(assemblyName);