Monday, April 11, 2011

Generating DLL assembly dynamically at run time.

Hello World! :-)

I have an interesting challenge that I'm wondering if anyone here can give me some direction.

Currently I have some code that is being generated dynamically. Another words a C# .cs file is created dynamically by this program, and the intention is to include this C# file in a project where you want to use it.

The challenge is that I would like to instead of generating a C# .cs file, I want to generate a .DLL file.

That way wherever you want to use this generated code, you can use it in any .NET language, and you would not be confined to C# since the code currently being generated is in C#. If I can figure out how to modify the generator (I wrote it so i have the source code) to create a DLL instead, it could be referenced by any kind of .NET application (not only C#) therefore it would be more usable.

What do you guys think? Thanks in advance.

From stackoverflow
  • This is very reasonable, in fact, it's what ASP.NET does. You'll still generate C# but then you'll want to compile it (with csc.exe).

  • using System.CodeDom.Compiler;
    using System.Diagnostics;
    using Microsoft.CSharp;
    
    CSharpCodeProvider codeProvider = new CSharpCodeProvider();
    ICodeCompiler icc = codeProvider.CreateCompiler();
    System.CodeDom.Compiler.CompilerParameters parameters = new CompilerParameters();
    parameters.GenerateExecutable = false;
    parameters.OutputAssembly = "AutoGen.dll";
    CompilerResults results = icc.CompileAssemblyFromSource(parameters, yourCodeAsString);
    

    Adapted from http://support.microsoft.com/kb/304655

  • Right now, your best bet is CSharpCodeProvider; the plans for 4.0 include "compiler as a service", which will make this fully managed.

0 comments:

Post a Comment