城堡的自代理构造函数? [英] Self-proxying constructor with Castle?

查看:150
本文介绍了城堡的自代理构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

类的构造函数是否可以将代理包装在自身周围?不幸的是,此代码导致StackOverflowException.

Is it possible for a class's constructor to wrap a proxy around itself? This code, unfortunately, causes a StackOverflowException.

void Main()
{
    var thing = new Thing();
}

public static readonly ProxyGenerator generator = new ProxyGenerator();

public class Thing
{
    public Thing()
    {
        generator.CreateClassProxyWithTarget(this);
    }
}

我想要某种方法来确保将类的新实例包装在代理中,而不必创建某种工厂来创建代理实例.

I want some way to guarantee that new instances of my class are wrapped in the proxy instead of having to create some kind of factory that creates proxied instance.

推荐答案

我最近来的是创建一个返回代理的Singleton. 这是一个示例:

The closest that I have come is creating a Singleton that returns a proxy. Here is an example:

public class MySingleton
{
    protected static MySingleton _instance = null;
    public static MySingleton Instance
    {
        get
        {
            if (_instance == null)
            {
                if (Simple.UseDynamicProxies)
                    _instance = Simple.GetProxy(typeof(MySingleton));
                else
                    _instance = new MySingleton();
            }
            return _instance;
        }
    }
}

请注意,Simple类具有实际创建代理,拦截和记录等的繁重工作"以及UseDynamicProxies标志,因此我可以在整个解决方案中打开/关闭代理使用.

Note that the Simple class holds the "heavy lifting" of actually creating a proxy, intercepting and logging, etc. as well as the UseDynamicProxies flag so I can turn on/off proxy usage throughout the solution.

这篇关于城堡的自代理构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆