简体   繁体   中英

How to keep dynamically loaded assemblies form breaking code at compile time?

I am linking one of the external resource at runetime in my code using something like below:

System.Reflection.Assembly assembly = System.Reflection.Assembly.LoadFrom("MyNice.dll");
            Type type = assembly.GetType("MyType");
            Tool = Activator.CreateInstance(type) as Tool;

Now as you can see that at the end of the object creation, it has to cast the resulting object into the tool class because there are a lot of references to the methods and properties of Tool class in my code that if it is no there then the code will error out on compile time.

Now, this is a bad situation because I wanted to remove the Dll from my references and have it loaded dynamically at runtime but at the same to there are pieces of my code that referes to and are dependent to the Tool assembly. How can I make it independent? Do I have to use reflection all over my code or there is any easy alternative out there?

for example:

if (Tool.ApplicationIsOpen)
                    return StatusResult.Success;

is there in the same class which assumes that Tool class already exists and will break if I remove it from my references folder.

Any suggesitons?

I would suggest making shared DLL to reference from both projects that contains an interface in which Tool inherits.

In this shared project, make an interface such as ITool, that exposes the functionality you need for the consumer project.

Shared Project

public interface ITool
{
    void Something();
}

Separate Project

public class Tool : ITool
{
    public void Something()
    {
        // do something
    }
}

Consumer Project

System.Reflection.Assembly assembly = System.Reflection.Assembly.LoadFrom("MyNice.dll");
Type type = assembly.GetTypes().FirstOrDefault(t => t.IsAssignableFrom(typeof(ITool)));
ITool tool = Activator.CreateInstance(type) as ITool;

Now you can delete the reference to the project containing Tool, but you still need the reference to the shared project that contains ITool. If you truly don't want any references, then explore the reflection route, but be warned it'll probably be messy.

This strategy is the basis for many plugin systems. I'd recommend you check out some Dependency Injection (DI for short) libraries that can do a lot of this heavy lifting for you.

Here is a list of DI libraries: http://www.hanselman.com/blog/ListOfNETDependencyInjectionContainersIOC.aspx Personally I've been using Ninject lately.

Some relevant links:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM