C# 从其他.dll加载服务并独立运行

C# 从其他.dll加载服务并独立运行,c#,.net,reflection,runtime,appdomain,C#,.net,Reflection,Runtime,Appdomain,我想以一种隔离的方式从不同的.dll运行几个服务。基本上,所有服务都源自RoleEntryPoint,我想将每个服务加载到一个单独的AppDomain中,并在不同的线程中运行它 到目前为止,我可以找到该服务并获取其类型: String pathToDll = @"C:\....\bin\Debug\ChildWorkerRole.dll"; Assembly assembly = Assembly.LoadFrom(pathToDll); Typ

我想以一种隔离的方式从不同的.dll运行几个服务。基本上,所有服务都源自
RoleEntryPoint
,我想将每个服务加载到一个单独的
AppDomain
中,并在不同的线程中运行它

到目前为止,我可以找到该服务并获取其类型:

        String pathToDll = @"C:\....\bin\Debug\ChildWorkerRole.dll"; 
        Assembly assembly = Assembly.LoadFrom(pathToDll);
        Type serviceType = assembly.GetTypes().SingleOrDefault(t => t.BaseType == typeof(RoleEntryPoint));
并在当前的
AppDomain
线程中运行它:

        RoleEntryPoint myRole2 = (RoleEntryPoint)Activator.CreateInstance(serviceType);
        if (myRole2.OnStart())
            myRole2.Run();
但当我尝试在不同AppDomain中的单独应用程序中运行它时,我遇到了一个异常:

        AppDomain domain = AppDomain.CreateDomain("MyNewDomain");
        RoleEntryPoint myRole = (RoleEntryPoint)domain.CreateInstanceFromAndUnwrap(pathToDll, serviceType.FullName);
        if (myRole.OnStart())
            myRole.Run();
System.Runtime.Serialization.SerializationException was unhandled
  Message=Type 'ChildWorkerRole.WorkerRole' in assembly 'ChildWorkerRole, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' is not marked as serializable.
  Source=mscorlib
  StackTrace:
       at System.AppDomain.CreateInstanceFromAndUnwrap(String assemblyName, String typeName)
.......
此例外情况:

        AppDomain domain = AppDomain.CreateDomain("MyNewDomain");
        RoleEntryPoint myRole = (RoleEntryPoint)domain.CreateInstanceFromAndUnwrap(pathToDll, serviceType.FullName);
        if (myRole.OnStart())
            myRole.Run();
System.Runtime.Serialization.SerializationException was unhandled
  Message=Type 'ChildWorkerRole.WorkerRole' in assembly 'ChildWorkerRole, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' is not marked as serializable.
  Source=mscorlib
  StackTrace:
       at System.AppDomain.CreateInstanceFromAndUnwrap(String assemblyName, String typeName)
.......
有趣的是,
ChildWorkerRole
实际上是用
SerializableAttribute
标记的。。。但可能是因为
RoleEntryPoint
不是,所以无法执行

有什么想法或解决办法吗


谢谢

为了在单独的AppDomain中使用类型,它以及您直接使用的所有类型都需要标记为
[Serializable]
,或者您需要从中派生它们

如果这是不可能的,唯一的实际选择是创建一个代理类,您可以使用它来遵循上述标准,并允许它在内部管理您的类型