Skip to content
This repository has been archived by the owner on Dec 14, 2018. It is now read-only.

Load custom assembly to ASP .NET Core 2.0 project #6756

Closed
tarekgh opened this issue Sep 3, 2017 · 12 comments
Closed

Load custom assembly to ASP .NET Core 2.0 project #6756

tarekgh opened this issue Sep 3, 2017 · 12 comments

Comments

@tarekgh
Copy link

tarekgh commented Sep 3, 2017

From @troncomputers on August 30, 2017 7:7

From @troncomputers on August 29, 2017 9:26

Hi!
I'm trying to load custom assembly (nip24Library.dll). This is the C# API for finding companies by VAT Number in Poland.

FileNotFoundException: Could not load file or assembly 'nip24Library, Version=1.3.1.0, Culture=neutral, PublicKeyToken=a3a1b0bb1b99a109'. Can not find the specified file.

VS added for me this entry to .csproj file

  <ItemGroup>
    <Reference Include="nip24Library">
      <HintPath>C:\OptimoKasiarz\OptimoKasiarz\bin\Debug\netcoreapp2.0\nip24Library.dll</HintPath>
      <Private>true</Private>
    </Reference>
  </ItemGroup>

It looks like the web app doesn't know where this file is. How can I solve this problem?

Copied from original issue: dotnet/aspnetcore#2171

Copied from original issue: dotnet/corefx#23678

@tarekgh
Copy link
Author

tarekgh commented Sep 3, 2017

From @troncomputers on August 30, 2017 7:7

From @Tratcher on August 29, 2017 17:23

You should move this to https://github.com/dotnet/corefx.

@tarekgh
Copy link
Author

tarekgh commented Sep 3, 2017

From @karelz on August 30, 2017 17:28

Do you have a minimal repro?
Did you try to load the DLL into Console app? Does that work?

@tarekgh
Copy link
Author

tarekgh commented Sep 3, 2017

@troncomputers How nip24Library.dll is built?

CC @weshaggard @ericstj

@tarekgh
Copy link
Author

tarekgh commented Sep 3, 2017

From @troncomputers on August 31, 2017 7:20

@karelz Works fine with workaround with Visual Studio
@tarekgh I don't know how. You can download it from here:
nip24Library
PS. "Pobierz" means "Download" ;)
As far as I know I'd use this workaround:

    public class ReferencesMetadataReferenceFeatureProvider : IApplicationFeatureProvider<MetadataReferenceFeature>
    {
        public void PopulateFeature(IEnumerable<ApplicationPart> parts, MetadataReferenceFeature feature)
        {
            var libraryPaths = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
            foreach (var assemblyPart in parts.OfType<AssemblyPart>())
            {
                var dependencyContext = DependencyContext.Load(assemblyPart.Assembly);
                if (dependencyContext != null)
                {
                    foreach (var library in dependencyContext.CompileLibraries)
                    {
                        if (string.Equals("reference", library.Type, StringComparison.OrdinalIgnoreCase))
                        {
                            foreach (var libraryAssembly in library.Assemblies)
                            {
                                libraryPaths.Add(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, libraryAssembly));
                            }
                        }
                        else
                        {
                            foreach (var path in library.ResolveReferencePaths())
                            {
                                libraryPaths.Add(path);
                            }
                        }
                    }
                }
                else
                {
                    libraryPaths.Add(assemblyPart.Assembly.Location);
                }
            }

            foreach (var path in libraryPaths)
            {
                feature.MetadataReferences.Add(CreateMetadataReference(path));
            }
        }

        private static MetadataReference CreateMetadataReference(string path)
        {
            using (var stream = File.OpenRead(path))
            {
                var moduleMetadata = ModuleMetadata.CreateFromStream(stream, PEStreamOptions.PrefetchMetadata);
                var assemblyMetadata = AssemblyMetadata.Create(moduleMetadata);

                return assemblyMetadata.GetReference(filePath: path);
            }
        }
    }

and in Startup.cs

            services.AddMvc().ConfigureApplicationPartManager(manager =>
            {
                var oldMetadataRefernceFeatureProvider = manager.FeatureProviders.First(f => f is MetadataReferenceFeatureProvider);
                manager.FeatureProviders.Remove(oldMetadataRefernceFeatureProvider);
                manager.FeatureProviders.Add(new ReferencesMetadataReferenceFeatureProvider());
            });

It's working now when I launch app from Visual Studio, not working after publish and open from IIS server. On page where I'm using nip24 I'm getting HTTP ERROR 500

[EDIT] Fix C# syntax highlight by @karelz

@tarekgh
Copy link
Author

tarekgh commented Sep 3, 2017

From @karelz on August 31, 2017 16:0

Works fine with workaround with Visual Studio

@troncomputers what does it mean? Console app? Please provide more details on what works.
Note that if this is ASP.NET specific, this is not the right repo and we might need to reopen the one in ASP.NET repo. By creating small repro, you will help us identify which components is causing troubles.

@tarekgh
Copy link
Author

tarekgh commented Sep 3, 2017

From @ericstj on August 31, 2017 17:33

@eerhardt it would seem that this direct file reference isn't making it into the deps file.

@troncomputers it'd be good if you can provide an isolated repro solution that demonstrates this.

Also, I hate to suggest to move again, but I think this belongs in dotnet/sdk repo, but we can wait until we confirm that.

@tarekgh
Copy link
Author

tarekgh commented Sep 3, 2017

I couldn't repro this issue with simple netcoreapp 2.0 console app. I have referenced nip24Library.dll exactly as mentioned above and the app load it just fine.

NetCoreConsoleApp.zip

We'll not be able to help here without providing a simple repro project

@tarekgh
Copy link
Author

tarekgh commented Sep 3, 2017

From @troncomputers on September 1, 2017 9:56

It is NOT a console app. It's ASP .NET Core web app. Just create a Web Application project with ver. ASP .NET Core 2.0 and add nip24library.dll to reference and try to build/run/compile.

InvalidOperationException: Cannot find compilation library location for package 'nip24Library'
Microsoft.Extensions.DependencyModel.CompilationLibrary.ResolveReferencePaths(ICompilationAssemblyResolver resolver, List<string> assemblies)
Microsoft.Extensions.DependencyModel.CompilationLibrary.ResolveReferencePaths()
Microsoft.AspNetCore.Mvc.ApplicationParts.AssemblyPart+<>c.<GetReferencePaths>b__8_0(CompilationLibrary library)
System.Linq.Enumerable+SelectManySingleSelectorIterator.MoveNext()
Microsoft.AspNetCore.Mvc.Razor.Compilation.MetadataReferenceFeatureProvider.PopulateFeature(IEnumerable<ApplicationPart> parts, MetadataReferenceFeature feature)
Microsoft.AspNetCore.Mvc.ApplicationParts.ApplicationPartManager.PopulateFeature<TFeature>(TFeature feature)
Microsoft.AspNetCore.Mvc.Razor.Internal.DefaultRazorReferenceManager.GetCompilationReferences()
System.Threading.LazyInitializer.EnsureInitializedCore<T>(ref T target, ref bool initialized, ref object syncLock, Func<T> valueFactory)
Microsoft.AspNetCore.Mvc.Razor.Internal.DefaultRazorReferenceManager.get_CompilationReferences()
Microsoft.AspNetCore.Mvc.Razor.Internal.LazyMetadataReferenceFeature.get_References()
Microsoft.CodeAnalysis.Razor.CompilationTagHelperFeature.GetDescriptors()
Microsoft.AspNetCore.Razor.Language.DefaultRazorTagHelperBinderPhase.ExecuteCore(RazorCodeDocument codeDocument)
Microsoft.AspNetCore.Razor.Language.RazorEnginePhaseBase.Execute(RazorCodeDocument codeDocument)
Microsoft.AspNetCore.Razor.Language.DefaultRazorEngine.Process(RazorCodeDocument document)
Microsoft.AspNetCore.Razor.Language.RazorTemplateEngine.GenerateCode(RazorCodeDocument codeDocument)
Microsoft.AspNetCore.Mvc.Razor.Internal.RazorViewCompiler.CompileAndEmit(string relativePath)
Microsoft.AspNetCore.Mvc.Razor.Internal.RazorViewCompiler.CreateCacheEntry(string normalizedPath)
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Runtime.CompilerServices.TaskAwaiter.GetResult()
Microsoft.AspNetCore.Mvc.RazorPages.Internal.DefaultPageLoader.Load(PageActionDescriptor actionDescriptor)
Microsoft.AspNetCore.Mvc.RazorPages.Internal.PageActionInvokerProvider.OnProvidersExecuting(ActionInvokerProviderContext context)
Microsoft.AspNetCore.Mvc.Internal.ActionInvokerFactory.CreateInvoker(ActionContext actionContext)
Microsoft.AspNetCore.Mvc.Internal.MvcAttributeRouteHandler+<>c__DisplayClass12_0.<RouteAsync>b__0(HttpContext c)
Microsoft.AspNetCore.Builder.RouterMiddleware+<Invoke>d__4.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware+<Invoke>d__7.MoveNext()

@tarekgh
Copy link
Author

tarekgh commented Sep 3, 2017

From @ericstj on September 1, 2017 14:12

I believe this is the same as dotnet/sdk#1500, https://github.com/dotnet/core-setup/issues/2981. It looks like it's already being tracked for a fix in 2.0.1.

@tarekgh
Copy link
Author

tarekgh commented Sep 3, 2017

From @eerhardt on September 1, 2017 14:41

Yes, the error

InvalidOperationException: Cannot find compilation library location for package 'XXX'

where XXX is an assembly with a direct <Reference> in your .csproj is tracked by https://github.com/dotnet/core-setup/issues/2981. The workaround provided by @pranavkm at pranavkm/fix-ref@1b83ca5 should solve this issue until we can get a service release fix for it.

BTW - I don't think the fix will make it for 2.0.1, as we didn't have time. Instead, I think it will make it for 2.0.2.

@tarekgh
Copy link
Author

tarekgh commented Sep 3, 2017

From @troncomputers on September 2, 2017 22:23

Was Microsoft plannig to support only nuget packages for asp net core web pages or it is just a bug with new technology?

@Eilon
Copy link
Member

Eilon commented Sep 5, 2017

NuGet packages are certainly the best way to add references to other DLLs because they are better integrated with the build and publish process.

Having said that, the issues mentioned earlier are indeed bugs that we are planning to have fixes in upcoming patch releases.

@Eilon Eilon closed this as completed Sep 5, 2017
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants