dimanche 16 février 2020

Load class to program as assembly and find it in current domain

I want to dynamically load classes into my .NET Program. First of all i looking for specific classes that will implemented in this program:

public List<string> GetRegisteredAlgorithmNames()
{
    var interfacesNames = new List<string>();
    var assemblies = this.GetAlgorithmsAssemblies();
    assemblies.ForEach(a => interfacesNames.Add(a.Name));

    return interfacesNames;
}

private List<TypeInfo> GetAlgorithmsAssemblies()
{
    var algorithmAssembly = typeof(IAlgorithm).Assembly;
    var algorithmAssemblies = algorithmAssembly.DefinedTypes.Where(type =>
                type.ImplementedInterfaces.Any(i => i == typeof(IAlgorithm)) && type.IsClass).ToList();

    return algorithmAssemblies;
}

Basicly, i have three classes in my program that implements IAlgorithm interface. Now i want to implement functionality for uploading another imlpemented algorithms that implementIAlgorithm interface. For this purpose im using this method:

public void UploadAlgorithm()
{
    string filepath = this.fileDialog.GetAlgorithmImplementationFilepath();
    if (!filepath.Equals(string.Empty))
    {
        var provider = new CSharpCodeProvider();
        var options = new CompilerParameters
        {
            OutputAssembly = "Foo.dll"
        };
        string source = filepath;

        provider.CompileAssemblyFromSource(options, new[] { source });
    }
}

But when i want to check, if my newly created .dll exist in my program by this code:

AppDomain currentDomain = AppDomain.CurrentDomain;
Evidence asEvidence = currentDomain.Evidence;
var a = currentDomain.GetAssemblies();

There is no .dll called Foo.dll.

How to dynamically make .dll file from uploaded csharp class and then use it in my program like normal class (of course using reflection for it).





Aucun commentaire:

Enregistrer un commentaire