Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: How do I dynamically load/instantiate a DLL?

I've seen a couple examples out there that could possibly help me, but I don't have that much time to explore them as I just found out today that my bosses have to demo this a week earlier than planned, and I want to add this new functionality. I'll try and keep this short and sweet.

Ok, this is like my 10th time trying to right this to make it clear, hopefully it is. This is an application. Rows of data need to be displayed in a DataGridView (done). Some rows are highlighted differently based on reports (done). Most reports have their own SQL file and are implemented at runtime from an INI file (done). However, some reports need to call a Function. The application is using an SQLite database. I would like to have DLLs that are reports, all of the same format, and all of them return a List of ReportRecord. ReportRecord is a class defined in my main application but I would also define it in each DLL when they are created. I want to instantiate the DLL, call it's "GetRecords" function, and use it in my main application. Here is some psuedocode. If you guys can tell me if it's possible, or give me an idea of a better way to do this, I'd appreciate it.

PSUEDOCODE

 foreach (string str in System.IO.Directory.GetFiles("C:\\ReportDlls", "*.dll"))
 {
   //Instantiate DLL e.g. newReport
   //_lstReportRecords.AddRange(newReport.GetReportRecords());
 }    

Is there anyway to do this?

Currently, I have the following to supplement until I find this out:

        private void RefreshReports(string strReportTitle)
        {
            _lstReportRecords = _lstReportRecords.Where(rr => rr.Description != strReportTitle).ToList<ReportRecord>();
            string strColumn = iniFile.GetString(strReportTitle, "Column", "");


            if (strColumn != null)
            {
                _lstReportRecords.AddRange(_dataController.BuildReportList(strColumn, strReportTitle, GetReportSQL(strReportTitle)));
            }
            else
            {
                switch (strReportTitle)
                {
                    case "Improper Indenture":
                        _lstReportRecords.AddRange(_dataController.ImproperIndenture());
                        break;
                    case "Skipping Figure":
                        _lstReportRecords.AddRange(_dataController.SkippingFigure());
                        break;
                    default: break;
                }
            }
            FormatCells();
        }

Thanks everyone.

Edit: Sorry guys, looking at that stuff is honestly making me feel stupid. Like, my mind is going blank and all and can't concentrate on it. :) What you guys have provided is probably the best way, but since I have to have a quality Demo ready by Tuesday and there shouldn't be any more reports added needing functions until then, I'm going to keep this open. Once my boss is out of town to demo it, I'll work on implementing this. But right now, it's going to go unanswered unless I see an example that is very very (for 2 year olds) straight forward.

like image 886
XstreamINsanity Avatar asked Sep 09 '10 19:09

XstreamINsanity


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is C in C language?

What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.

Is C language easy?

C is a general-purpose language that most programmers learn before moving on to more complex languages. From Unix and Windows to Tic Tac Toe and Photoshop, several of the most commonly used applications today have been built on C. It is easy to learn because: A simple syntax with only 32 keywords.


2 Answers

You can simply create a C# library project implementing the interfaces below and store the binary file in the database or on the file system. You could then load the assembly from raw assembly bytes/file path an instantiate an object. With reflection you can also call the constructor directly, but i prefer the factory pattern for such tasks.

public interface IReportModule
{
}

public interface IReportModuleFactory
{
    IReportModule Create();
}

private static IReportModule CreateReportModuleFromRawAssemby(byte[] rawAssembly)
{
    var reportModule = Assembly.Load(rawAssembly);
    var factoryType = reportModule.GetExportedTypes()
        .FirstOrDefault(x => x.IsAssignableFrom(typeof(IReportModuleFactory)));
    if (factoryType != null)
    {
        var reportModuleFactory = (IReportModuleFactory)
            reportModule.CreateInstance(factoryType.FullName);
        return reportModuleFactory.Create();
    }
    else
        throw new NotImplementedException("rawAssembly does not implement IReportModuleFactory");
}
like image 102
Nappy Avatar answered Sep 24 '22 22:09

Nappy


Don't look at this in terms of DLL's, which are the raw files, but Assemblies, which is how .NET sees things. You can load an Assembly using Assembly.Load. Having said this, have you considered a more generic solution, such as inversion of control?

like image 36
Steven Sudit Avatar answered Sep 23 '22 22:09

Steven Sudit