c# - CaSTLe Windsor 代理生成选项

标签 c# castle-windsor castle-dynamicproxy

我一直在努力在网上找到任何东西,所以我想看看是否有其他人知道如何解决我遇到的这个小问题。

我有一个场景,我想创建一个代理对象,以便可以将各种其他接口(interface)添加到同一对象。到目前为止,我对此没有任何问题。我的其他要求之一是能够在代理生成的类上设置属性。

我已经能够手动使用 CaSTLe DynmaicProxy 成功地做到这一点,使用的是:

var serviceOptions = new ProxyGenerationOptions();

// Create MyAttribute
var args = new object[] { "SomeName" };
var constructorTypes = new[] { typeof(String) };
var constructorInfo = typeof(MyAttribute).GetConstructor(constructorTypes);
var attributeBuilder = new CustomAttributeBuilder(constructorInfo, args);

serviceOptions.AdditionalAttributes.Add(attributeBuilder);

但是,我正在使用 windsor 通过注入(inject)来解决我的依赖关系。 Windsor 确实提供了一些代理选项,例如:

configurer.Proxy.AdditionalInterfaces(interfaces);
configurer.Proxy.MixIns(r => r.Component(type));

但它似乎没有提供自定义属性的选项。有谁知道这是如何实现的?非常感谢。

最佳答案

最后,我从 Phil 的想法和扫描 CaSTLe 源代码中找到了替代解决方案。

我创建了一个自定义 ProxyFactory扩展 DefaultProxyFactory 的类来自 CaSTLe.Windsor 程序集。我实现的唯一方法是 CustomizeOptions方法,默​​认情况下为空。

从这里,我连接到 ExtendedPropertiesComponentModel获取 CustomAttributeBuilder 的集合我在注册组件时添加的实例。

完整代码如下:

internal const string PROXY_ATTRIBUTES_PROPERTY_KEY = "custom.proxy.attributes";

protected override void CustomizeOptions(ProxyGenerationOptions options, IKernel kernel, ComponentModel model, object[] arguments)
{
    if (model.ExtendedProperties.Contains(PROXY_ATTRIBUTES_PROPERTY_KEY))
    {
        var proxyAttributes = (IEnumerable<CustomAttributeBuilder>)model.ExtendedProperties[PROXY_ATTRIBUTES_PROPERTY_KEY];
        foreach (var attribute in proxyAttributes)
        {
            options.AdditionalAttributes.Add(attribute);
        }
    }

    base.CustomizeOptions(options, kernel, model, arguments);
}

configurer.ExtendedProperties(new Property(CustomProxyFactory.PROXY_ATTRIBUTES_PROPERTY_KEY, configurator.ProxySettings.CustomAttributes));

关于c# - CaSTLe Windsor 代理生成选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28855347/

相关文章:

c# - C# 中的一个接口(interface)和两个实现类(代理)

c# - .NET Task 实例能否在运行期间超出范围?

c# - 使用 ASP.net C# 从 html 选择列表中获取所有项目

c# - HangFire with CaSTLe Windsor 在后台作业中使用依赖项

c# - ASP.NET MVC3 Controller AOP 代理不拦截所有方法,只有 IController.Execute

c# - Opengl 和 opencl 在单个共享上下文中只能使用 1 个内核

c# - 城堡 IOC - 解决循环引用

c# - ASP.net MVC 4 - CaSTLe Windsor - 找不到方法 : 'System. Web.Http.Services.DependencyResolver

c# - 使用autofac和dynamicproxy2选择性拦截方法

c# - 用 Ninject 拦截。无法加载 IProxyRequestFactory