C# 如何使DLL访问加载它的exe应用程序中的类/对象
我有一个C#exe应用程序,它加载一个DLL运行时,我想知道DLL如何访问应用程序的公共静态类???这个问题可以通过第三个DLL解决,该DLL只包含契约和常用的东西。我将在契约程序集中声明一个接口,并将实现它的对象注入动态加载的类中 不能使用静态类,因为它们不能实现接口。如果您需要一些静态的东西,那么使用singleton模式C# 如何使DLL访问加载它的exe应用程序中的类/对象,c#,dll,C#,Dll,我有一个C#exe应用程序,它加载一个DLL运行时,我想知道DLL如何访问应用程序的公共静态类???这个问题可以通过第三个DLL解决,该DLL只包含契约和常用的东西。我将在契约程序集中声明一个接口,并将实现它的对象注入动态加载的类中 不能使用静态类,因为它们不能实现接口。如果您需要一些静态的东西,那么使用singleton模式 // In the Contracts assembly // Defines the same functionality as was in your static
// 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();
}
用法
这通常是由提供接口的dll和实现该接口的主应用程序完成的,然后将实现的实例传递回dll的代码 例如,在库(dll)中: 然后在应用程序代码中:
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();
}
}
由于静态类不能直接实现接口,因此在这种情况下需要使用适配器模式。拥有一个实现接口的类,并且只将其调用传递给静态类的方法。你不能。应用程序需要对DLL的引用,而DLL则需要对应用程序的引用。这会创建一个无法处理的循环引用。DLL通常是为了可重用性而创建的,因此不应引用特定的应用程序。你想干什么?
// 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();
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();
}
}