Workarounds for referencing third-party DLLs in ASP. NET CORE MVC 2.0 Project-invalidoperationexception:cannot find compilation library location for package

Source: Internet
Author: User

Today, in learning ASP. NET core MVC, I was delighted to see that Microsoft resumed its ability to allow developers to reference third-party DLL assemblies in ASP. NET Core MVC 2.0. So I hurried to write a demo to try, my project structure is as follows:

As you can see in the solution for two projects, Aspnetcorewebapp is an ASP. NET Core MVC 2.0 project, and Mynetcorelib is a class library project To show that Aspnetcorewebapp is referencing mynetcorelib through assemblies, I also created a folder called reference in the solution, The DLL files that were generated by the class library project Mynetcorelib compiled are placed in the reference folder and then referenced in Aspnetcorewebapp by adding a reference assembly, as shown in:

Then compile the entire solution, debug Aspnetcorewebapp This project, run the error immediately ... The error is as follows:

This is obviously a run-time error, because I was successful in compiling the entire solution without reporting any errors. Then went online to check the information, It is found that although we have referenced MyNetCoreLib.dll in the project Aspnetcorewebapp, and the project Aspnetcorewebapp compiled, it also outputs the MyNetCoreLib.dll file in its bin directory, as shown in:

But the dependency injection environment of ASP. NET CORE mvc doesn't really know where to look for MyNetCoreLib.dll this file, so it's going to run the times out Invalidoperationexception:cannot find Compilation Library location for package ' Mynetcorelib ' this error ... Developers need to use code to tell where ASP. NET CORE MVC should go to find the MyNetCoreLib.dll file.

So first we need to define a class called Metadatareferencefeatureprovider, the code below, whose key code is to tell the ASP. MVC's Dependency Injection environment go to AppDomain.CurrentDomain.BaseDirectory (that is, the bin directory) to find the assembly file we referenced in the project

usingMicrosoft.AspNetCore.Mvc.ApplicationParts;usingMicrosoft.AspNetCore.Mvc.Razor.Compilation;usingmicrosoft.codeanalysis;usingMicrosoft.Extensions.DependencyModel;usingSystem;usingSystem.Collections.Generic;usingSystem.IO;usingSystem.Linq;usingSystem.Reflection.PortableExecutable;usingSystem.Threading.Tasks;namespaceaspnetcorewebapp.utils{ Public classReferencesmetadatareferencefeatureprovider:iapplicationfeatureprovider<metadatareferencefeature>    {         Public voidPopulatefeature (ienumerable<applicationpart>parts, metadatareferencefeature feature) {            varLibrarypaths =Newhashset<string>(stringcomparer.ordinalignorecase); foreach(varAssemblyPartinchParts. Oftype<assemblypart>())            {                varDependencycontext =dependencycontext.load (assemblypart.assembly); if(Dependencycontext! =NULL)                {                    foreach(varLibraryinchdependencycontext.compilelibraries) {if(string. Equals ("Reference", library. Type, StringComparison.OrdinalIgnoreCase)) {foreach(varlibraryassemblyinchLibrary. assemblies) {//tell ASP. NET CORE MVC If you now have a reference to a third-party assembly in your project, go to the AppDomain.CurrentDomain.BaseDirectory folder (which is the bin directory) to look for the assembly's DLL fileLibrarypaths.add (Path.Combine (AppDomain.CurrentDomain.BaseDirectory, libraryassembly))                            ; }                        }                        Else                        {                            foreach(varPathinchLibrary.                            Resolvereferencepaths ()) {librarypaths.add (path); }                        }                    }                }                Else{librarypaths.add (assemblyPart.Assembly.Location); }            }            foreach(varPathinchlibrarypaths) {feature.            Metadatareferences.add (createmetadatareference (path)); }        }        Private StaticMetadatareference Createmetadatareference (stringpath) {            using(varstream =file.openread (path)) {                varModulemetadata =Modulemetadata.createfromstream (stream, pestreamoptions.prefetchmetadata); varAssemblymetadata =assemblymetadata.create (Modulemetadata); returnassemblymetadata.getreference (Filepath:path); }        }    }}

Next we also register the provider of our definition on the SERVICES.ADDMVC () method in the Startup.cs file of the project Aspnetcorewebapp, the code is as follows (note the code in the Configureservices method):

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Threading.Tasks;usingMicrosoft.AspNetCore.Builder;usingMicrosoft.AspNetCore.Hosting;usingMicrosoft.Extensions.Configuration;usingMicrosoft.Extensions.DependencyInjection;usingMicrosoft.AspNetCore.Mvc.Razor.Compilation;usingaspnetcorewebapp.utils;namespaceaspnetcorewebapp{ Public classStartup { PublicStartup (iconfiguration configuration) {Configuration=configuration; }         PublicIConfiguration Configuration {Get; } //This method gets called by the runtime. Use this method to add services to the container.         Public voidconfigureservices (iservicecollection services) {services. Addmvc (). Configureapplicationpartmanager (Manager=            {                //removes the default built-in Metadatareferencefeatureprovider in the ASP. NET CORE MVC Manager, or throws InvalidOperationException if the provider is not removed: Cannot find compilation library location for package ' Mynetcorelib ' this errorManager. Featureproviders.remove (manager. Featureproviders.first (f = f ismetadatareferencefeatureprovider)); //Register our defined referencesmetadatareferencefeatureprovider to ASP. MVC Manager to replace the metadatareferencefeatureprovider removed aboveManager. Featureproviders.add (NewReferencesmetadatareferencefeatureprovider ());        }); }        //This method gets called by the runtime. Use this method to configure the HTTP request pipeline.         Public voidConfigure (Iapplicationbuilder app, Ihostingenvironment env) {if(env. Isdevelopment ()) {app.                Usedeveloperexceptionpage (); App.            Usebrowserlink (); }            Else{app. Useexceptionhandler ("/home/error"); } app.            Usestaticfiles (); App. USEMVC (Routes={routes. MapRoute (Name:"default", Template:"{controller=home}/{action=index}/{id?}");        }); }    }}

Then recompile the code, debug the project Aspnetcorewebapp, OK This project runs successfully, no errors are reported.

I don't know if this is a flaw in ASP. NET CORE MVC 2.0, will it be fixed in a later release, or is Microsoft intentionally doing it? Because I tried. In the console project for. NET CORE 2.0, referencing a third-party assembly DLL file directly is no problem, and you can use it without writing any extra code. Since Microsoft has also opened the ability to reference third-party assemblies in ASP. NET core MVC, it can actually do exactly the same thing as the old. Later versions of MVC can improve this functionality, eliminating the need for developers to add additional code after referencing DLL files.

Workarounds for referencing third-party DLLs in ASP. NET CORE MVC 2.0 Project-invalidoperationexception:cannot find compilation library location for package

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.