Eroor在单独的appdomain中加载DLL [英] Eroor in loading DLL in seperate appdomain

查看:54
本文介绍了Eroor在单独的appdomain中加载DLL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

HI,



我创建了一个AppDomain,并希望在其中加载并运行一个dll以及一些Io权限集。我可以创建创建实例但是无法加载程序集。我无法识别我正在做的错误,但加载程序集时出现以下错误消息。能否请你帮忙/纠正我:



错误信息:





I have created one AppDomain and would like load and run one dll with in it along with some Io permission set. I could create the create the instance but have been failing to load the Assembly. I could not recognize the mistake that I am doing however the following error message while loading the assembly. Could you please help/correct me on this:

Error Message:

"

Additional information: Request for the permission of type 'System.Security.Permissions.FileIOPermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.





堆栈跟踪:



"

stack Trace:

at System.Security.CodeAccessSecurityEngine.Check(Object demand, StackCrawlMark& stackMark, Boolean isPermSet)
at System.Security.CodeAccessSecurityEngine.Check(CodeAccessPermission cap, StackCrawlMark& stackMark)
at System.Security.CodeAccessPermission.Demand()
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.InternalLoadFrom(String assemblyFile, Evidence securityEvidence, Byte[] hashValue, AssemblyHashAlgorithm hashAlgorithm, Boolean forIntrospection, Boolean suppressSecurityChecks, StackCrawlMark& stackMark)
at System.Reflection.Assembly.LoadFrom(String assemblyFile)
at AppDomainSample.AppDomainSample.ThrirdPartyDomainLoader.LoadAssembly(String dllPath)
at AppDomainSample.AppDomainSample.ThrirdPartyDomainLoader.LoadAssembly(String dllPath)
at AppDomainSample.AppDomainSample.Main() in D:\DotNetTraining0504\AppDomainSample\AppDomainSample\AppDomainSample.cs:line 34
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()





我的尝试:





What I have tried:

using System;
using System.Reflection;
using System.Configuration;

namespace AppDomainSample
{
    public class AppDomainSample 
    {
        public static void Main()
        {
            var generateFilesPluginPath = ConfigurationManager.AppSettings["GenerateFilesPlugin"];
            var generateFilesPluginPathName = ConfigurationManager.AppSettings["GenerateFilesPluginName"];

            var appDomainSetup = new AppDomainSetup
            {
                ApplicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase
            };


            var permissionSet = AppDomainPermissionSets.GetFileIOPermissionset();

            var generateFilesAppDomain = AppDomain.CreateDomain(
                generateFilesPluginPathName,
                null,
                appDomainSetup,
                permissionSet);

            var thrirdPartyDomainLoader =
                (ThrirdPartyDomainLoader)
                generateFilesAppDomain.CreateInstanceAndUnwrap(
                    typeof(ThrirdPartyDomainLoader).Assembly.FullName,
                    typeof(ThrirdPartyDomainLoader).FullName);

            thrirdPartyDomainLoader.LoadAssembly(@"D:\EpamDotNetTraining0504\AppDomainSample\GenerateFilesPlugin\bin\Debug\GenerateFilesPlugin.dll");

            thrirdPartyDomainLoader.MethodInvoker(
                ApplicationBase(generateFilesPluginPath),
                "GenerateFilesPlugin.GenerateFiles",
                "CreateFile",
                 @"D:\",
                "temp.text");

            AppDomain.Unload(generateFilesAppDomain);

            Console.ReadLine();
        }

        public class ThrirdPartyDomainLoader : MarshalByRefObject
        {
            private Assembly _assembly;

            public void LoadAssembly(string dllPath)
            {
               var  _assembly = Assembly.LoadFrom(dllPath);
            }

            public void MethodInvoker(string dllpath, string className, string methodName, params object[] parameters)
            {
                var assm = Assembly.LoadFile(dllpath);

                var type1 = assm.GetType(className);

                var genericInstance = Activator.CreateInstance(type1);

                var method = type1.GetMethod(methodName);

                object obje = null;
                try
                {
                    obje = method.Invoke(genericInstance, new object[] { 1, 2 });
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }

                Console.WriteLine(obje);
            }
        }

        public static string ApplicationBase(string path)
        {
            var appDomainSetup = new AppDomainSetup { ApplicationBase = path };

            return appDomainSetup.ApplicationBase;
        }
    }
}







许可应用于AppDomain的集合




Permission sets applied for the AppDomain

public static class AppDomainPermissionSets
{
    public static PermissionSet GetFileIOPermissionset()
    {
        var permissionSet = new PermissionSet(PermissionState.None);
        permissionSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));

        permissionSet.AddPermission(
            new FileIOPermission(
                FileIOPermissionAccess.Write,
                ConfigurationManager.AppSettings["GenerateFilesPluginRestrictedPath"]));

        return permissionSet;
    }

}





第三方Dll中的逻辑:





Logic in 3rd party Dll:

using System;
using System.IO;

namespace GenerateFilesPlugin
{
    public class GenerateFiles
    {
        public bool CreateFile(string path, string file)
        {
            if (path == null || file == null)
            {
                Console.WriteLine("Invalid Input");

                return false;
            }

            try
            {
                File.Create(Path.Combine(path, file));

                return true;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

            return false;
        }
    }
}

推荐答案

似乎在IIS下运行网站的用户没有这样做的权限(加载外部程序集)...

尝试下列其中一项:

1.切换usr(它有利于测试,但可能不适合实际环境)

2.将信任级别设置为完整:设置信任级别(IIS 7) [ ^ ]
It seems the user running the site under IIS has no permissions to do that (to load external assemblies)...
Try one of these:
1. Switch usr (it is good for testing, but maybe improper for real environment)
2. Set trust level to full: Set a Trust Level (IIS 7)[^]


这篇关于Eroor在单独的appdomain中加载DLL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆