Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading an Assembly if a certain Attribute is present

Ok, here is the deal:

I want to load a user defined Assembly into my AppDomain, but I only want to do so if the specified Assembly matches some requirements. In my case, it must have, among other requirements, an Assembly level Attribute we could call MandatoryAssemblyAttribute.

There are two paths I can go as far as I see:

  1. Load the Assembly into my current AppDomain and check if the Attribute is present. Easy but inconvenient as I'm stuck with the loaded Assembly even if it doesnt have the MandatoryAssemblyAttribute. Not good.

  2. I can create a new AppDomain and load the Assembly from there and check if my good old MandatoryAddemblyAttribute is present. If it is, dump the created AppDomain and go ahead and load the Assembly into my CurrentAppDomain, if not, just dump the new AppDomain, tell the user, and have him try again.

Easier said than done. Searching the web, I've found a couple of examples on how to go about this, including this previous question posted in SO:Loading DLLs into a separate AppDomain

The problem I see with this solution is that you actually have to know a type (full name) in the Assembly you want to load to begin with. That is not a solution I like. The main point is trying to plug in an arbitrary Assembly that matches some requirements and through attributes discover what types to use. There is no knowledge beforehand of what types the Assembly will have. Of course I could make it a requirement that any Assembly meant to be used this way should implement some dummy class in order to offer an "entry point" for CreateInstanceFromAndUnwrap. I'd rather not.

Also, if I go ahead and do something along this line:

using (var frm = new OpenFileDialog())
{
    frm.DefaultExt = "dll";
    frm.Title = "Select dll...";
    frm.Filter = "Model files (*.dll)|*.dll";
    answer = frm.ShowDialog(this);

     if (answer == DialogResult.OK)
     {
          domain = AppDomain.CreateDomain("Model", new Evidence(AppDomain.CurrentDomain.Evidence));

          try
          {
              domain.CreateInstanceFrom(frm.FileName, "DummyNamespace.DummyObject");
                    modelIsValid = true;
          }
          catch (TypeLoadException)
          {
              ...
          }
          finally
          {
              if (domain != null)
                   AppDomain.Unload(domain);
          }
     }
}

This will work fine, but if then I go ahead and do the following:

foreach (var ass in domain.GetAssemblies()) //Do not fret, I would run this before unloading the AppDomain
    Console.WriteLine(ass.FullName); 

I get a FileNotFoundException. Why?

Another path I could take is this one: How load DLL in separate AppDomain But I'm not getting any luck either. I'm getting a FileNotFoundException whenever I choose some random .NET Assembly and besides it defeats the purpose as I need to know the Assembly's name (not file name) in order to load it up which doesn't match my requirements.

Is there another way to do this barring MEF (I am not targeting .NET 3.5)? Or am I stuck with creating some dummy object in order to load the Assembly through CreateInstanceFromAndUnwrap? And if so, why can't I iterate through the loaded assemblies without getting a FileNotFoundException? What am I doing wrong?

Many thanks for any advice.

like image 993
InBetween Avatar asked Oct 27 '11 16:10

InBetween


1 Answers

The problem I see with this solution is that you actually have to know a type (full name) in the Assembly

That is not quite accurate. What you do need to know is a type name is some assembly, not necessarily the assembly you are trying to examine. You should create a MarshalByRef class in your assembly and then use CreateInstanceAndUnwrap to create an instance of it from your own assembly (not the one you are trying to examine). That class would then do the load (since it lives in the new appdomain) and examine and return a boolean result to the original appdomain.

Here is some code to get you going. These classes go in your own assembly (not the one you are trying to examine):

This first class is used to create the examination AppDomain and to create an instance of your MarshalByRefObject class (see bottom):

using System;
using System.Security.Policy;

internal static class AttributeValidationUtility
{
   internal static bool ValidateAssembly(string pathToAssembly)
   {
      AppDomain appDomain = null;
      try
      {
         appDomain = AppDomain.CreateDomain("ExaminationAppDomain", new Evidence(AppDomain.CurrentDomain.Evidence));

         AttributeValidationMbro attributeValidationMbro = appDomain.CreateInstanceAndUnwrap(
                              typeof(AttributeValidationMbro).Assembly.FullName,
                              typeof(AttributeValidationMbro).FullName) as AttributeValidationMbro;

         return attributeValidationMbro.ValidateAssembly(pathToAssembly);
      }
      finally
      {
         if (appDomain != null)
         {
            AppDomain.Unload(appDomain);
         }
      }
   }
}

This is the MarshalByRefObject that will actually live in the new AppDomain and will do the actual examination of the assembly:

using System;
using System.Reflection;

public class AttributeValidationMbro : MarshalByRefObject
{
   public override object InitializeLifetimeService()
   {
      // infinite lifetime
      return null;
   }

   public bool ValidateAssembly(string pathToAssembly)
   {
      Assembly assemblyToExamine = Assembly.LoadFrom(pathToAssembly);

      bool hasAttribute = false;

      // TODO: examine the assemblyToExamine to see if it has the attribute

      return hasAttribute;
   }
}
like image 121
Russell McClure Avatar answered Sep 21 '22 11:09

Russell McClure