-1

I have a ASP.NET MVC application and a plugin that needs to write to the web.config file. For various reasons, I've found that the most appropriate way to do this is during compilation using MSBuild configuration, so I have created an executable distributed with my plugin to be called here with appropriate parameters for resolving consumer-application dependencies like the path to the config file.

The plugin is configurable, and the definition for this must be in the consumer application in a specific class.

Now the plugin-executable has to be able to read this class, but we can not have any hard-coded dependencies since the plugin should be distributable and used in many different applications.

I have found this answer here on SO about dynamically loading/unloading DLLs, and my question is if this is the approach to use, while passing in the relevant parameters as arguments to the exe, or do I have any other options?

Community
  • 1
  • 1
Alex
  • 14,104
  • 11
  • 54
  • 77

1 Answers1

1

The answer is Yes but you can do it in two different ways.

If you want to unload the class yes you need to create a new AppDomain, use it and unload it in the end, to do this you need a class that implements MarshalByRefObject it's much more complicated.

If the class can live during the lifetime of the client application you just need to load your plugin to the current AppDomain.

AppDomain.CurrentDomain.CreateInstanceAndUnwrap(assemblyName, typeName);

I strongly recommend that the instance you are loading implements a specific Interface so you can inspect a folder for DLL's like this

var ass = Assembly.LoadFrom(path);
ass.DefinedTypes.Where(t => t.ImplementedInterfaces
                             .Any(i => i.AssemblyQualifiedName ==
                                       typeof(<Defined Interface>).AssemblyQualifiedName))

this will return a list of types that implement your interface so you just need to use the above code to create one instance.

I think that to work with msbuild you need to take the first approach and do all the load unload and usage inside of the class that implements MarshalByRefObject don't quote me on this one.

Pedro.The.Kid
  • 1,968
  • 1
  • 14
  • 18