Об ошибке при загрузке библиотеки DLL в отдельном домене приложения
ПРИВЕТ,
Я создал один домен приложения и хотел бы загрузить и запустить в нем одну библиотеку dll вместе с некоторым набором разрешений ввода-вывода. Я мог бы создать экземпляр create the, но мне не удалось загрузить сборку. Я не мог распознать ошибку,которую я делаю, однако следующее сообщение об ошибке при загрузке сборки. Не могли бы вы помочь / поправить меня в этом вопросе:
сообщение об ошибке:
"
Additional information: Request for the permission of type 'System.Security.Permissions.FileIOPermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed."
трассировка стека:
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()
Что я уже пробовал:
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; } } }
Наборы разрешений, применяемые для домена приложения
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; } }
Логика в 3-й партии 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; } } }