在AppDomain中加载WCF库时无法加载文件或程序集

时间:2012-10-30 07:59:47

标签: wcf appdomain

我有一个带服务库的WCF服务。我想在新的AppDomain中创建一个类库实例,但这会抛出异常:

  

无法加载文件或程序集“ClassLibrary1.dll”或其依赖项之一。

 //Class library
 public class Class1 : MarshalByRefObject
 {    
        public string Method1(int i)
        {
            return "int=" + i;
        }
 }

//Class WCF Service
public class Service1 : IService1
{
     public string GetData(int value)
     {
          string name = typeof(Class1).Assembly.GetName().FullName;
          string type_name = typeof(Class1).FullName;
          var _Dom = AppDomain.CreateDomain("SubDomain", null, info);

          //why is it not working? 
          //exception - not found assembly file
          var _Factory = _Dom.CreateInstanceAndUnwrap(name, type_name) as Class1;

          //it's worked
          //var _Factory = AppDomain.CurrentDomain.CreateInstanceAndUnwrap(name, type_name) as Class1;

          return _Factory.Method1(value);
     }
}

//Client method to service
static void Main(string[] args)
{
    using (Service1Client cc = new Service1Client())
    {
        Console.WriteLine("Client opened.");
        Console.Write("Enter integer: ");

        int i = 0;
        int.TryParse(Console.ReadLine(), out i);
        try
        {
            var r = cc.GetData(i);
            Console.WriteLine(r);
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }
        cc.Close();
        Console.WriteLine("Client closed. Press Enter key to exit...");
        Console.ReadLine();
    }
}

Link to solution

2 个答案:

答案 0 :(得分:0)

//自托管解决了问题

Uri url = new Uri("http://localhost:7777/Service1");
using (ServiceHost host = new ServiceHost(typeof(Service1), url))
{
    host.AddServiceEndpoint(typeof(IService1), new WSHttpBinding(), "");
    ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
    smb.HttpGetEnabled = true;
    host.Description.Behaviors.Add(smb);
    host.Open();
}

答案 1 :(得分:0)

设置AppDomains基本目录和相关目录至少为我解决了这个问题

string basePath = AppDomain.CurrentDomain.BaseDirectory;
string relativePath = AppDomain.CurrentDomain.RelativeSearchPath;
m_domain = AppDomain.CreateDomain("MyDomain", null, basePath, relativePath, false);