Last active
April 8, 2019 20:52
-
-
Save dg1an3/dc639bca0555d24902194f9f5909df03 to your computer and use it in GitHub Desktop.
generate a dynamic empty wcf interface, given a name and namespace
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
string source = string.Format(@" | |
using System.ServiceModel; | |
namespace CreateTypeForSvcNamespace | |
{{ | |
[ServiceContract(Namespace=""{0}"",Name=""{1}"")] | |
public interface {1} {{ }} | |
}}", ns, name); | |
var asmName = Path.GetRandomFileName(); | |
var compilation = CSharpCompilation.Create(asmName, | |
syntaxTrees: | |
new[] | |
{ | |
CSharpSyntaxTree.ParseText(source) | |
}, | |
references: | |
new List<Type> | |
{ | |
typeof(object), | |
typeof(ServiceContractAttribute) | |
}.Select(tp => MetadataReference.CreateFromFile(tp.Assembly.Location)) | |
.ToArray(), | |
options: | |
new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); | |
Assembly asm = null; | |
using (var ms = new MemoryStream()) | |
{ | |
EmitResult result = compilation.Emit(ms); | |
if (!result.Success) | |
{ | |
throw new InvalidDataException(result.ToString()); | |
} | |
ms.Seek(0, SeekOrigin.Begin); | |
asm = Assembly.Load(ms.ToArray()); | |
} | |
var svcType = asm.GetTypes()[0]; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment