user1227445
user1227445

Reputation: 453

Reference Two DLLs with the same namespaces and types

I have two versions of the same DLL, i.e. LibV1.dll and LibV2.dll. Both libraries have the same namespaces and types, but are not compatible. I need to be able to reference both at the same time in a VB.Net project in order to upgrade data from the old version to the new version. This seems to be quite easy to solve in C#, but everything I've read indicates that there is no solution to this in VB.Net. In fact, I see this post from 2011, which confirms this. I'm wondering however if there has been any changes in the past 4 years that might make this possible now?

Upvotes: 5

Views: 252

Answers (1)

TnTinMn
TnTinMn

Reputation: 11791

Sorry, I had hoped to paste this a comment, but SO prevents me from doing so.

As far as I know, VB has not added the C# Aliasing feature, but your assertion that there is no solution in VB.Net is incorrect.

Your referenced post from 2011 points you to using Reflection as a workaround. I think the simplest route would be to choose which DLL you want to have Intellisense support for and add a reference to that DLL. Then you can use Reflection.Assembly.LoadFile to get a reference to the second DLL and use the CreateInstance method on that instance to create an Object reference to a needed class. You would the use late-binding to work with that class instance. Alternatively, you could use Reflection to get the needed MethodInfo's/PropertyInfo's/etc. and work through them to work on the class instance, but I think that would be a lot more work than using late-binding.

Edited to add example.

Sub Test()
    ' assume you chose Version 2 as to reference in your project
    ' you can create an instance of its classes directly in your code 
    ' with full Intellisense support

    Dim myClass1V2 As New CommonRootNS.Class1

    ' call function Foo on this instance
    Dim resV2 As Int32 = myClass1V2.foo

    ' to get access to Version 1, we will use Reflection to load the Dll

    ' Assume that the Version 1 Dll is stored in the same directory as the exceuting assembly
    Dim path As String = IO.Path.GetDirectoryName(Reflection.Assembly.GetExecutingAssembly.Location)

    Dim dllVersion1Assembly As Reflection.Assembly
    dllVersion1Assembly = Reflection.Assembly.LoadFile(IO.Path.Combine(path, "Test DLL Version 1.dll"))

    ' now create an instance of the Class1 from the Version 1 Dll and store it as an Object
    Dim myClass1V1 As Object = dllVersion1Assembly.CreateInstance("CommonRootNS.Class1")

    ' use late binding to call the 'foo' function. Requires Option Strict Off
    Dim retV1 As Int32 = myClass1V1.foo
End Sub

Upvotes: 3

Related Questions