gpt4 book ai didi

c# - Spring AOP + MVVM基础+ PropertyChanged

转载 作者:行者123 更新时间:2023-12-03 10:50:22 25 4
gpt4 key购买 nike

我将Spring.Net 1.3.1与MVVM Foundation一起使用,将横切应用于我的 View 模型。我注意到,如果在将对象转换为代理进行跨切之前分配了属性更改的处理程序,则代理引擎不会将属性更改的处理程序应用于代理。有谁知道这是否是预期的行为,如果是,是否有解决方法?

我的工厂看起来像这样

public static class AopProxyFactory {
public static object GetProxy(object target) {
var factory = new ProxyFactory(target);

factory.AddAdvisor(new Spring.Aop.Support.DefaultPointcutAdvisor(
new AttributeMatchMethodPointcut(typeof(AttributeStoringMethod)),
new UnitValidationBeforeAdvice())
);

factory.AddAdvice(new NotifyPropertyChangedAdvice());
factory.ProxyTargetType = true;

return factory.GetProxy();
}
}

建议看起来像这样
    public class UnitValidationBeforeAdvice : IMethodBeforeAdvice {
public UnitValidationBeforeAdvice() {
}

public void Before(MethodInfo method, object[] args, object target) {
if (args.Length != 1) {
throw new ArgumentException("The args collection is not valid!");
}

var canConvertTo = true;
if (!canConvertTo) {
throw new ArgumentException("The '{0}' cannot be converted.");
}
}
}

public class NotifyPropertyChangedAdvice : IAfterReturningAdvice, INotifyPropertyChanged {
public event PropertyChangedEventHandler PropertyChanged;

public void AfterReturning(object ReturnValue, MethodInfo Method, object[] Args, object Target) {
if (Method.Name.StartsWith("set_")) {
RaisePropertyChanged(Target, Method.Name.Substring("set_".Length));
}
}

private void RaisePropertyChanged(Object Target, String PropertyName) {
if (PropertyChanged != null)
PropertyChanged(Target, new PropertyChangedEventArgs(PropertyName));
}
}

我代理的对象看起来像这样
    public class ProxyTypeObject : ObservableObject {
private string whoCaresItsBroke;
public string WhoCaresItsBroke {
get { return whoCaresItsBroke; }
set {
whoCaresItsBroke = value;
RaisePropertyChanged("WhoCaresItsBroke");
}
}
}

和调用代码
var pto = new ProxyTypeObject();
pto.WhoCaresItsBroke = "BooHoo";
pto.PropertyChanged += (object sender, System.ComponentModel.PropertyChangedEventArgs e) => {
return;
};

var proxy = AopProxyFactory.GetProxy(pto);
(proxy as ProxyTypeObject).WhoCaresItsBroke = "BooHoo2";

您会注意到,当我设置“WhoCaresItsBroke”属性时,我之前连接的属性更改处理程序将永远不会受到影响。 (我尝试使用spring.net论坛中提供的NotifyPropertyChangedAdvice,但似乎不起作用。)

最佳答案

似乎Spring示例Spring.AopQuickStart\src\Spring.AopQuickStart.Step6所做的几乎与您尝试做的事情相同(拦截Property的[自动生成] setter )。
您可能想看看the source of the example

关于c# - Spring AOP + MVVM基础+ PropertyChanged,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5836605/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com