如何使DLL访问加载它的exe应用程序中的类/对象

本文关键字:应用程序 对象 exe DLL 访问 加载 何使 | 更新日期: 2023-09-27 18:07:35

我有一个加载DLL运行时的c# exe应用程序,我想知道DLL如何访问应用程序的公共静态类?

如何使DLL访问加载它的exe应用程序中的类/对象

这个问题可以通过只包含契约和常用内容的第三个DLL来解决。我将在契约程序集中声明一个接口,并将实现它的对象注入动态加载的类中。

不能使用静态类,因为它们不能实现接口。如果你需要一些静态的东西,那么就使用单例模式。

// In the Contracts assembly
// Defines the same functionality as was in your static class.
public interface IServiceContract
{
    void SomeServiceMethod();
}
// For the classes dynamically loaded from the DLL
public interface IAddIn
{
    void TestMethod();
}

// In the dynamically loaded assembly
public class AddInClass : IAddIn
{
    private IServiceContract _service;
    public AddInClass(IServiceContract service)
    {
        _service = service;
    }
    public void TestMethod()
    {
        _service.SomeServiceMethod();
    }
}

// In the main assembly (exe)
public class ImplementsServiceContract : IServiceContract
{
    public void SomeServiceMethod()
    {
        Console.WriteLine("Hello world!");
    }
}
使用

IServiceContract service = new ImplementsServiceContract();
Assembly assembly = Assembly.LoadFile(@"C:'myDll.dll");
var type = assembly.GetType("AddInClass");
IAddIn addIn = (IAddIn)Activator.CreateInstance(type, service);
addIn.TestMethod();

这通常是通过dll提供一个接口,主应用程序实现该接口,然后将实现的实例传递回dll代码来完成的。

例如,在库(dll)中:

public interface IDependency
{
    void DoThing();
}
public class MyLibraryClass
{
    IDependency _dependency;
    public MyLibraryClass(IDependency dependency)
    {
        _dependency = dependency;
    }
    public void MyUsefulMethod()
    {
        //Some stuff
        _dependency.DoThing();
        //Some more stuff
    }
}

然后在应用程序代码中:

public class ConcreteDependency : IDependency
{
    public void DoThing()
    {
        //Implementation here
    }
}
public class MyClassThatUsesTheLibrary()
{
    public void MyMethod()
    {
        var dependency = new ConcreteDependency();
        var libraryClass = new MyLibraryClass(dependency);
        libraryClass.MyUsefulMethod();
    }
}
由于静态类不能直接实现接口,在这种情况下,您需要使用适配器模式。有一个实现接口的类,它只是把它的调用传递给静态类的方法。