简体   繁体   English

使用温莎城堡时如何注入属性

[英]How to inject properties when using Castle Windsor

I am new to IOC. 我是IOC的新手。

I've MethodProfilerAspectAttribute attribute which has to be applied on any method like this 我有MethodProfilerAspectAttribute属性,必须将其应用于任何此类方法

[MethodProfilerAspectAttribute(5)]
public void MethodName(){}

Here is the implementation of MethodProfilerAspectAttribute 这是MethodProfilerAspectAttribute的实现

[Serializable]
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
public sealed class MethodProfilerAspectAttribute : OnMethodBoundaryAspect
{
        public ILogger logger { get; set; }
        public int x{get;set;}
        public MethodProfilerAspectAttribute(int x)
        {
            this.x=x;
        }
    public override void OnSuccess(MethodExecutionArgs args)
        {
            logger.CustomLogging("logMe");
            base.OnSuccess(args);
        }
}

I want to resolve my ILogger dependency using Log4NetLogger which is registered and resolving constructor dependencies properly by using following : 我想使用已注册的Log4NetLogger解决我的ILogger依赖关系,并使用以下方法正确解析构造函数的依赖关系:

container.Register(Component.For<ILogger>().ImplementedBy(typeof(Log4NetLogger)));

but unfortunately whatever I've tried for resolving property dependency, is not working. 但不幸的是,我为解决属性依赖所做的任何尝试都无法正常工作。

Any help would be greatly appreciated. 任何帮助将不胜感激。

The link you provided just describes property injection for components resolved from the container. 您提供的链接仅描述了从容器解析的组件的属性注入。 Attributes are not resolved from the container, but instead are created by the CLR. 属性不是从容器解析的,而是由CLR创建的。 You might be able to jigger a way to set attribute properties by providing a custom IContributeComponentModelConstruction implementation, but I'm not so sure. 您可能可以通过提供自定义的IContributeComponentModelConstruction实现来设置属性属性的方法,但是我不确定。 See answers for similar questions here , here , and here (from the creator of Windsor). 在此处此处此处 (来自Windsor的创建者),请参见类似问题的答案。

In any case, attributes is not where you want to put functionality. 无论如何,属性不是您要放置功能的地方。 They should be minimal, just providing metadata. 它们应该最少,仅提供元数据。 I see here you're trying to provide some sort of functionality across all method invocations. 我在这里看到您正在尝试在所有方法调用中提供某种功能。 You may want to consider Windsor's interceptors to provide similar behavior. 您可能需要考虑使用温莎的拦截器来提供类似的行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM