其他.dll文件加载的服务和运行它们隔离加载、文件、dll

2023-09-03 20:39:17 作者:含笑带泪

我想在一个单独的运行方式,从不同的.dll的多个服务。基本上,所有的服务都是由 RoleEntryPoint 导出,我想加载每一个在分离的AppDomain 在它上面运行在不同的线程。

I'd like to run several services from different .dll's in a isolated way. Basically, all services are derived from RoleEntryPoint , and I want to load each one in a separated AppDomain and run it there in a different thread.

到目前为止,我可以找到服务,并得到它的类型:

So far, I can locate the service and get its type:

        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一个单独的运行它,我得到一个异常:

But when I try to run it in a separate in different AppDomain I get an exception:

        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 则不然,它无法做到的。

The funny thing is that ChildWorkerRole is actually marked with the SerializableAttribute ... but may be because RoleEntryPoint is not, it cannot be done.

任何想法或变通方法?

谢谢!

推荐答案

为了同一个类型在一个单独的AppDomain工作,这和你直接使用的类型,需要作标记为 [Serializable接口] ,或者你需要从他们获得MarshalByRefObject.

In order to work with a type in a separate AppDomain, it, and all of the types you directly use, need to be either marked as [Serializable], or you need to derive them from MarshalByRefObject.

如果这是不可能的,唯一真正的选择是使你可以使用不遵循上述标准的代理类,并允许它在内部管理的类型。

If this is not possible, the only real option is to make a proxy class that you can use which does follow the above criteria, and allow it to manage your types internally.