我在我的项目中使用 CaSTLe Windsor。拦截了一些已注册的组件。因为组件是通过接口(interface)注册的,所以 CaSTLe Windsor 创建了接口(interface)代理(CaSTLe Windsor 创建了一个独立的类型来实现接口(interface)并通过使用组合委托(delegate)给真正的实现)。不幸的是,您不能在接口(interface)的实际实现中执行方法,因为代理会被绕过。
有没有办法在真实实现中获取代表真实实现的代理实例?
这是我想要实现的示例。我想始终拦截 Get 方法。请不要提供其他方法来重构此示例,因为这不是我的生产代码,而只是为了演示而发明的东西。
public interface IProvider
{
bool IsEmpty { get; }
object Get();
}
public class ProxyBypassingProvider : IProvider
{
public bool IsEmpty
{
// Calls method directly, not through the proxy.
get { return Get() == null; }
}
public object Get()
{
return new Object();
}
}
public class InterceptedProvider : IProvider
{
private IProvider _this; // Should hold the proxy instance.
public bool IsEmpty
{
// Calls method through proxy.
get { return _this.Get() == null; }
}
public object Get()
{
return new Object();
}
}
如何将字段 _this 设置为代理实例?
最好的问候
奥利弗·哈纳皮
PS:这是一个真实世界的例子。
public interface IPresentationModel
{
IView View { get; }
}
public interface IView
{
void SetModel(IPresentationModel model);
}
public PresentationModel : IPresentationModel
{
public IView View { get; private set; }
public PresentationModel(IView view)
{
View = view;
View.SetModel(this);
}
}
我正在解析 transient 表示模型。它注入(inject)了一个 transient View 。因为 View 需要知道表示模型,所以表示模型调用 IView.SetModel(this) 让 View 知道它的表示模型。
现在的问题是,尽管已解析的 IPresentationModel 是一个代理,但 SetModel 方法只获得真正的实现。因此,当 View 调用表示模型上的方法时,不会触发任何拦截器。
到目前为止,我找到的唯一解决方案是在解析完呈现模型后手动设置 View 的呈现模型。
var model = _container.Resolve<IPresentationModel>();
model.View.SetModel(model);
我认为,这个解决方案并没有真正很好地解决。
最佳答案
这就是所谓的“leaking this”问题,接口(interface)代理没有很好的解决方法。
您提到的合成后步骤可能是最好的解决方案。您可以使用金枪鱼的 OnCreateFacility - 它被烘焙到主干中,或者如果你不想在主干上运行,你可以从存储库中复制代码并与 v2.0 一起使用。
关于c# - 温莎城堡 : How to retrieve proxy for specific instance?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1410351/