AppDomain.Load()无法加载,出现FileNotFoundException错误。

8

我正在尝试将我的插件dll加载到单独的AppDomain中,但是Load()方法失败并出现FileNotFoundException。此外,设置AppDomainSetup的PrivateBinPath属性似乎没有效果,因为在日志中我看到“Initial PrivatePath = NULL”。所有插件都有强名称。通常每个插件存储在[应用程序启动路径]\postplugins\[插件目录]中。如果我将插件子目录放在[应用程序启动路径]目录下,一切正常。我还尝试手动更改AppBase属性,但它不起作用。
以下是代码:

public void LoadPostPlugins(IPluginsHost host, string pluginsDir)
    {
        _Host = host;
        var privatePath = "";
        var paths = new List<string>();
        //build PrivateBinPath
        var dirs = new DirectoryInfo(pluginsDir).GetDirectories();
        foreach (var d in dirs)
        {
            privatePath += d.FullName;
            privatePath += ";";
        }
        if (privatePath.Length > 1) privatePath = privatePath.Substring(0, privatePath.Length - 1);
        //create new domain
        var appDomainSetup = new AppDomainSetup { PrivateBinPath = privatePath };
        Evidence evidence = AppDomain.CurrentDomain.Evidence;
        var sandbox = AppDomain.CreateDomain("sandbox_" + Guid.NewGuid(), evidence, appDomainSetup);
        try
        {
            foreach (var d in dirs)
            {
                var files = d.GetFiles("*.dll");
                foreach (var f in files)
                {
                    try
                    {
                        //try to load dll - here I get FileNotFoundException
                        var ass = sandbox.Load(AssemblyName.GetAssemblyName(f.FullName));
                        var f1 = f;
                        paths.AddRange(from type in ass.GetTypes()
                                       select type.GetInterface("PluginsCore.IPostPlugin")
                                       into iface
                                       where iface != null
                                       select f1.FullName);
                    }
                    catch (FileNotFoundException ex)
                    {
                        Debug.WriteLine(ex);
                    }
                }
            }
        }
        finally
        {
            AppDomain.Unload(sandbox);
        }
        foreach (var plugin in from p in paths
                               select Assembly.LoadFrom(p)
                                   into ass
                                   select
                                       ass.GetTypes().FirstOrDefault(t => t.GetInterface("PluginsCore.IPostPlugin") != null)
                                       into type
                                       where type != null
                                       select (IPostPlugin)Activator.CreateInstance(type))
        {
            plugin.Init(host);
            plugin.GotPostsPartial += plugin_GotPostsPartial;
            plugin.GotPostsFull += plugin_GotPostsFull;
            plugin.PostPerformed += plugin_PostPerformed;
            _PostPlugins.Add(plugin);
        }
    }

以下是日志记录:

'FBTest.vshost.exe' (Managed (v4.0.30319)): Loaded 'D:\VS2010Projects\PNotes - NET\pnfacebook\FBTest\bin\Debug\postplugins\pnfacebook\pnfacebook.dll', Symbols loaded.
A first chance exception of type 'System.IO.FileNotFoundException' occurred in FBTest.exe
System.IO.FileNotFoundException: Could not load file or assembly 'pnfacebook, Version=1.0.0.0, Culture=neutral, PublicKeyToken=9e2a2192d22aadc7' or one of its dependencies. The system cannot find the file specified.
File name: 'pnfacebook, Version=1.0.0.0, Culture=neutral, PublicKeyToken=9e2a2192d22aadc7'
   at System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
   at System.Reflection.RuntimeAssembly.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
   at System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, RuntimeAssembly reqAssembly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
   at System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean forIntrospection)
   at System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection)
   at System.Reflection.Assembly.Load(String assemblyString)
   at System.UnitySerializationHolder.GetRealObject(StreamingContext context)

   at System.AppDomain.Load(AssemblyName assemblyRef)
   at PNotes.NET.PNPlugins.LoadPostPlugins(IPluginsHost host, String pluginsDir) in D:\VS2010Projects\PNotes - NET\pnfacebook\FBTest\PNPlugins.cs:line 71


=== Pre-bind state information ===
LOG: User = ANDREYHP\Andrey
LOG: DisplayName = pnfacebook, Version=1.0.0.0, Culture=neutral, PublicKeyToken=9e2a2192d22aadc7
 (Fully-specified)
LOG: Appbase = file:///D:/VS2010Projects/PNotes - NET/pnfacebook/FBTest/bin/Debug/
LOG: Initial PrivatePath = NULL
Calling assembly : (Unknown).
===
LOG: This bind starts in default load context.
LOG: No application configuration file found.
LOG: Using host configuration file: 
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework\v4.0.30319\config\machine.config.
LOG: Post-policy reference: pnfacebook, Version=1.0.0.0, Culture=neutral, PublicKeyToken=9e2a2192d22aadc7
LOG: Attempting download of new URL file:///D:/VS2010Projects/PNotes - NET/pnfacebook/FBTest/bin/Debug/pnfacebook.DLL.
LOG: Attempting download of new URL file:///D:/VS2010Projects/PNotes - NET/pnfacebook/FBTest/bin/Debug/pnfacebook/pnfacebook.DLL.
LOG: Attempting download of new URL file:///D:/VS2010Projects/PNotes - NET/pnfacebook/FBTest/bin/Debug/pnfacebook.EXE.
LOG: Attempting download of new URL file:///D:/VS2010Projects/PNotes - NET/pnfacebook/FBTest/bin/Debug/pnfacebook/pnfacebook.EXE.
2个回答

21

当您以这种方式将程序集加载到AppDomain中时,使用的是当前 AppDomain 的 PrivateBinPath 来查找程序集。

对于您的示例,当我将以下内容添加到我的 App.config 文件中时,它可以正常运行:

<runtime>
  <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
    <probing privatePath="[PATH_TO_PLUGIN]"/>
  </assemblyBinding>
</runtime>

不过,这对您来说并没有太大的用处。

我所做的是创建一个新的程序集,其中包含IPostPlugin和IPluginsHost接口,还有一个名为Loader的类,其代码如下:

public class Loader : MarshalByRefObject
{
    public IPostPlugin[] LoadPlugins(string assemblyName)
    {
        var assemb = Assembly.Load(assemblyName);

        var types = from type in assemb.GetTypes()
                where typeof(IPostPlugin).IsAssignableFrom(type)
                select type;

        var instances = types.Select(
            v => (IPostPlugin)Activator.CreateInstance(v)).ToArray();

        return instances;
    }
}

我将新的程序集保存在应用程序根目录中,不需要存在于插件目录中(它可以存在,但由于优先搜索应用程序根目录,所以不会被使用)。

然后在主 AppDomain 中,我改为这样做:

sandbox.Load(typeof(Loader).Assembly.FullName);

Loader loader = (Loader)Activator.CreateInstance(
    sandbox,
    typeof(Loader).Assembly.FullName,
    typeof(Loader).FullName,
    false,
    BindingFlags.Public | BindingFlags.Instance,
    null,
    null,
    null,
    null).Unwrap();

var plugins = loader.LoadPlugins(AssemblyName.GetAssemblyName(f.FullName).FullName);

foreach (var p in plugins)
{
    p.Init(this);
}

_PostPlugins.AddRange(plugins);

所以,我创建了一个已知的Loader类型实例,然后让它从插件AppDomain内部创建插件实例。这样就可以按照你想要的方式使用PrivateBinPaths。

还有一件事,私有bin路径可以是相对路径,因此你可以添加pluginsDir + Path.DirectorySeparatorChar + d.Name而不是添加d.FullName,以使最终路径列表更短。但这只是我的个人偏好!希望这可以帮到你。


1
James,非常感谢!终于我看到了有关使用MarshalByRefObject的清晰解释。不幸的是,我没有足够的声望来标记答案为有用(至少需要15个):( - dedpichto
当我尝试这样做时,虽然我将LoadPlugins方法设置为通用的,但我仍然遇到了SerializationException。有什么建议吗?我可以看到该程序集已在沙盒应用程序域中加载。 - Emil Badh
1
@JamesThurley 实现 IPostPlugin 的类需要继承自 MarshalByRefObject 吗?这样可以在沙盒域中执行代码,而不必将其加载到主域中。 - JoeBrockhaus
+1 谢谢!这个方法可以在插件接口程序集中实例化 Loader 内部的插件。然而,由于具体类型必须被主应用程序所知才能进行反序列化,因此对于插件机制来说并不令人满意。我现在能够执行插件,但是我不能保持其实例处于活动状态,因为我只能将调用结果发送回主应用程序,而不能发送插件本身实现的接口。 - Elo

0
非常感谢 DedPicto 和 James Thurley,他们帮助我实现了完整的解决方案,我在this post中发布了它。
我遇到了与 Emil Badh 相同的问题:如果您尝试从“Loader”类返回表示当前 AppDomain 中未知具体类的接口,则会出现“序列化异常”。
这是因为具体类型试图进行反序列化。 解决方案:我能够从“Loader”类返回“自定义代理”的具体类型,并且它可以工作。有关详细信息,请参见引用的帖子:
// Our CUSTOM PROXY: the concrete type which will be known from main App
[Serializable]
public class ServerBaseProxy : MarshalByRefObject, IServerBase
{
    private IServerBase _hostedServer;

    /// <summary>
    /// cstor with no parameters for deserialization
    /// </summary>
    public ServerBaseProxy ()
    {

    }

    /// <summary>
    /// Internal constructor to use when you write "new ServerBaseProxy"
    /// </summary>
    /// <param name="name"></param>
    public ServerBaseProxy(IServerBase hostedServer)
    {
        _hostedServer = hostedServer;
    }      

    public string Execute(Query q)
    {
        return(_hostedServer.Execute(q));
    }

}

这个代理可以被返回并用作真实的具体类型!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接