类库在使用时丢失引用(dll)

时间:2016-02-06 17:10:40

标签: c# dll reference assemblies class-library

对不起标题。我不知道如何快速描述这个问题。 我的问题是我的class-libraryreferences to other (third party) DLLs。 我需要在另一个项目中使用这个类库,所以我显然将我的类库的.dll添加到我的主项目中。

当我开始我的主项目时,总是出现一个错误,即我的类库中的引用(dll)无法找到。

如果我将整个类库作为项目添加到visual studio中的projectmap,然后引用整个项目,则不会发生此错误。

我真的不想将整个班级库作为一个项目添加到每个"主机" - 我做的项目中。

有没有人知道为什么在添加类库的.dll时会出现此错误,而不是在添加类库的整个项目作为参考时?

即使我没有将整个库项目作为参考添加,也必须有一个解决方案才能使其正常工作。否则制作类库没有任何意义,对吧?

顺便说一句:我的类库包含第三方dll,第三方dll的本地副本属性设置为true。

提前致谢!

修改: 我的目标是真正使类库可移植,即使它包含第三方库。我想只将.dll提供给另一台电脑并使用它而不必每次都添加整个类库项目。

1 个答案:

答案 0 :(得分:1)

错误是因为您没有在第二个项目上复制dll,您添加了对dll的引用以便复制,但不会复制dll的引用你的dll,所以缺少库。

或者您使用dll重新分发依赖项,或者您可以将dll作为资源嵌入到dll中,然后拦截程序集加载并通过资源提供它:http://blogs.msdn.com/b/microsoft_press/archive/2010/02/03/jeffrey-richter-excerpt-2-from-clr-via-c-third-edition.aspx

编辑:为了在dll中执行它,你需要使用静态类并在使用任何依赖于其他库的类之前调用​​静态初始化器。

以下是一个示例设置:

- 一个名为LibraryB的库,它提供了一个这样的简单类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LibraryB
{
    public class ReferencedClass
    {
        public int GetIt()
        {

            return 5;

        }
    }
}

- 一个名为LibraryA的库,它引用了LibraryB并提供了两个类,初始化器和真实类:

<强>初始化程序

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace LibraryA
{
    public static class Initializer
    {
        public static void Init()
        {
            AppDomain.CurrentDomain.AssemblyResolve += (sender, args) =>
            {

                if (!args.Name.StartsWith("LibraryB"))
                    return null;

                return Assembly.Load(LibraryA.Properties.Resources.LibraryB);

            }; 
        }
    }
}

<强>类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LibraryA
{
    public class RealClass
    {
        public int DoIt()
        {

            LibraryB.ReferencedClass cl = new LibraryB.ReferencedClass();
            return cl.GetIt();

        }
    }
}

LibraryA还将LibraryB.dll编译库作为资源嵌入。

- 一个名为Test的项目,仅引用LibraryA:

using LibraryA;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Initializer.Init();
            RealClass c = new RealClass();
            Console.WriteLine("From LibraryA: " + c.DoIt());
            Console.ReadKey();
        }
    }
}

如果你设置正确并且你执行它它会工作,请记住,如果你通过visual studio,vs将复制dll以便在编译所有复制exe和之后进行真正的测试LibraryA和execute,它将在没有LibraryB的情况下工作,LibraryB正在使用LibraryB。