2014-10-16 43 views
1

我正在编写一个需要使用.NET Remoting与服务器进行通信的小型应用程序。我使用AutoFac注册我的情况下,跑在何时被布置我的远程代理对象的一个​​问题,下面是一些示例代码:处理“远程处理代理对象”生命期的建议方法

 builder.Register(b => 
     { 
      var channel = new TcpClientChannel(); 
      // ... 
      var remoteObj = (IMyComponent)Activator.GetObject(typeof(IMyComponent), "tcp://..."); 
      return remoteObj; 
     }).As<IMyComponent>(); 

     // ... and then when using it: 

     using (var scope = this.container.BeginLifetimeScope()) { 

      var myComponent = scope.Resolve<IMyComponent>(); 

     } // <= An exception will be thrown here since AutoFac will try to call .Dispose on myComponent 

     // Later I realized that the exception can be fixed by specifying an "empty" OnRealease-behavior when registering the component, probably because AutoFac doesnt try to treat MyComponent like an IDisposable. 
     ... 
     }).As<MyIComponent>().OnRelease(c => { //Manual disposing here }); 

此异常引起了我的怀疑,如果我做的东西完全错在这里以及如何正确处理远程代理的生命周期。我的方法有什么不妥,即通过AutoFac“创建”并返回远程代理?如果是这样,远程代理服务器的生命周期应该如何处理?

回答

1

There are some detailed docs on how Autofac handles disposal on the Autofac doc site.这可能有助于清除您的一些问题。

如果您有一个IDisposable组件,您不希望Autofac为您调用Dispose,请将其注册为ExternallyOwned,并且自动处置将被禁用。

+0

感谢您的回答,ExternallyOwned将在这个特定的例子中有所需的效果(不要处置),虽然我的问题更多的是“处理远程处理对象的生命期的方法”。 – 2014-10-20 05:38:46