0

I am stuck for 3rd day with this problem and I have no freaking idea why this doesn't work. I just want to load external .dll to read some info using reflection and delete the file after all. The problem is that read files are locked. The most strange thing is that only two files are locked while i read 5 of them succesfully. I've tried ShadowCopy with no result. I got no clue right now.

This is my appdomain class:

public class AppDomainExpander
    {
        private Type[] _types;
        public Type[] Types
        {
            get { return _types; }
            set { _types = value; }
        }
        public void Create(string domainName, string path)
        {
            AppDomainSetup aps = new AppDomainSetup();
            aps.ShadowCopyFiles = "true";
            AppDomain dmn = AppDomain.CreateDomain(domainName);
            string typename = typeof(DomainCommunicator).FullName;
            string assemblyName = typeof(DomainCommunicator).Assembly.FullName;
            var inner = (DomainCommunicator)dmn.CreateInstanceAndUnwrap(assemblyName, typename);
            inner.Create();
            Assembly assembly = Assembly.LoadFrom(path);
            Types = assembly.GetTypes();
            AppDomain.Unload(dmn); //it's strange that the code even work because i try to unload domain before i get Types[]
        }
        public class DomainCommunicator : MarshalByRefObject
        {
            public void Create()
            {
                AppDomain.CurrentDomain.DomainUnload += new EventHandler(OnDomainUnload);
            }

            void OnDomainUnload(object sender, EventArgs e)
            {
                AppDomain.CurrentDomain.DomainUnload -= new EventHandler(OnDomainUnload);
            }
        }  
    }  

And this is how i try to use it:

var expander = new AppDomainExpander();
expander.Create("MyDomain", file.Path);
foreach (var type in expander.Types)
tshepang
  • 12,111
  • 21
  • 91
  • 136
Mateusz Gaweł
  • 673
  • 1
  • 8
  • 22

2 Answers2

1

The types are loaded to your main AppDomain which does not have the ShadowCopy feature enabled. This is why the files are locked.

You will need to load the assembly in the DomainCommunicator.Create method instead. Note though that you cannot keep the Types property. This will lead to types leaking from the child AppDomain to the main one and the file locking problems that you currently face.

Panos Rontogiannis
  • 4,154
  • 1
  • 24
  • 29
0

I just noticed that only interfaces are locked. What is more when I load two classes and then two interfaces it's OK. But when I add interface and implementing class at same time it locks

Mateusz Gaweł
  • 673
  • 1
  • 8
  • 22