How do I load a type from another assembly when in a Web App?
I have this existing code:
Private Function GetTypeFromName(ByVal FullTypeName As String, ByVal AssemblyName As String) As Type
Dim DirStr = New FileInfo(System.Reflection.Assembly.GetExecutingAssembly.Location).DirectoryName
Dim Asm = [Assembly].LoadFile(DirStr & "\" & AssemblyName & ".dll")
Return Asm.GetType(FullTypeName)
End Function
The result of a call to this routine is a Type which will then be instantiated and used within the app.
Previous use and Assumptions
This code was previously used in a Winforms app to locate a type based on data loaded from a config file and passed into this function.
Generally the Assembly sought is already referenced by t开发者_如何学运维he application, but this is not always the case.
As you can see, the code currently expects the assembly name to be passed in without a ".dll" suffix or a path and is further assumed to be resident in the same folder as the executing assembly.
These assumptions have been correct until now.
Everything Changes
Now I am executing this code from within a Web App and it seems that the folder of the executing assembly is...
C:\Windows\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\<assemblyName>\ae5faeca\7d2a827f\assembly\dl3\212260f8\0af7415f_9747cc01\<assemblyName>.DLL
...and further there are no other dlls in this folder.
I expected that this folder would be the bin folder of my web app and that all other assemblies would be available from there.
So... How do I load a type from another assembly when in a Web App?
What you need to do is ensure the assembly you are trying to load either lives within the websites directory (bin, app_data, etc).
After that you need to do a HttpServerUtility.MapPath to the directory you expect the assembly to be in. Once you have that, you'll be able to load it.
Private Function GetTypeFromName(ByVal FullTypeName As String, ByVal AssemblyName As String) As Type
Dim DirStr = HttpServerUtility.MapPath( "/bin" ) //assuming you are loading from the bin directory of your website
Dim Asm = [Assembly].LoadFile(DirStr & "\" & AssemblyName & ".dll")
Return Asm.GetType(FullTypeName)
End Function
MSDN for HttpServerUtility http://msdn.microsoft.com/en-us/library/system.web.httpserverutility.mappath.aspx
Hope this helps
精彩评论