简体   繁体   English

在运行时使用引用的程序集进行编译

[英]Compile at runtime with referenced assemblies

I have created a function to compile C# code in a string in memory and use it at runtime. 我创建了一个函数,用于在内存中的字符串中编译C#代码并在运行时使用它。 It works very well. 效果很好。

Next I created a small class library (lets call it mynew.dll) and placed it at c:\\mylibraries\\mynew.dll. 接下来,我创建了一个小型类库(将其称为mynew.dll),并将其放置在c:\\ mylibraries \\ mynew.dll中。

In my code I can add a referenced assembly. 在我的代码中,我可以添加一个引用的程序集。 I do it like this: 我这样做是这样的:

CSharpCodeProvider provider = new CSharpCodeProvider();
CompilerParameters parameters = new CompilerParameters
{
    GenerateExecutable = false,
    GenerateInMemory = true
};

parameters.ReferencedAssemblies.Add(@"c:\mylibraries\mynew.dll");

CompilerResults results = provider.CompileAssemblyFromSource(parameters, mycode);

Now, in my C# code-string (mycode) is a function called "Execute". 现在,在我的C#代码字符串(mycode)中是一个名为“ Execute”的函数。 When I declare the namespace and class from the mynew.dll in this function I get this error: 当我在此函数中从mynew.dll声明名称空间和类时,出现以下错误:

Could not load file or assembly 'MyNew, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. 无法加载文件或程序集“ MyNew,Version = 1.0.0.0,Culture = neutral,PublicKeyToken = null”或其依赖项之一。 The system cannot find the file specified. 该系统找不到指定的文件。

When I copy the dll in the bin/debug folder of the main application is suddenly works, but I don't want this. 当我将dll复制到主应用程序的bin / debug文件夹中时,它突然起作用了,但我不希望这样做。 I want the code, that is compiled at runtime, to use it, not the main application. 我希望在运行时编译的代码使用它,而不是主应用程序。

This I did before posting here: 我在这里发布之前所做的:

  • Search Stackoverflow 搜索堆栈溢出
  • Used Google 二手谷歌
  • Tried to compile the dll to the disk and not in memory. 试图将dll编译到磁盘而不是内存中。 This works... Problem now is that the dll is locked in IIS and I cannot delete it without restarting the IIS server; 这行得通...现在的问题是,该dll被锁定在IIS中,如果不重新启动IIS服务器,我将无法删除它; no option since the code can change any moment and I don't want to restart the server when people are on the website. 没有选择,因为代码可以随时更改,并且当人们在网站上时,我不想重新启动服务器。

Is there a way to fix this? 有没有办法解决这个问题?

Use Directory.GetFiles to find your assembly in the file system, use System.Reflection.Assembly.LoadFile to load the assembly, and then find the types required. 使用Directory.GetFiles在文件系统中找到您的程序集,使用System.Reflection.Assembly.LoadFile加载程序集,然后找到所需的类型。 Use interface that will be implemented by your concrete classes to avoid having to know the concrete types. 使用将由您的具体类实现的接口,以避免必须了解具体类型。

This thread should help: Finding objects that implement interface from loaded assembly -how to compare types? 该线程应该有所帮助: 从加载的程序集中查找实现接口的对象-如何比较类型?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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