gpt4 book ai didi

c# - AOP、Unity、方法的拦截

转载 作者:行者123 更新时间:2023-11-30 15:41:44 27 4
gpt4 key购买 nike

我刚刚开始使用 Unity 和拦截功能。我创建了一个原型(prototype)来验证限制或功能,在我看来,为了拦截一个方法,必须满足几个条件。特别是在我看来,类或接口(interface)必须通过容器来解析。那是对的吗?有没有什么方法可以让我在没有这个要求的情况下做到这一点。

我可能误解了如何正确使用它,因为那里有很多旧的和不完整的信息,但没有很好的工作示例。

我会更新一些代码。请记住,这个东西中有成千上万行代码,所以改变这个糟糕的设计不是一个选项,也超出了当前项目的范围。


public interface IApoClass
{
[LoggingCallHandler]
void SomeAbstractAopMethod(string abstractparam);
[LoggingCallHandlerAttribute]
void SomeVirtualAopMethod(string virtualparam);
}
public abstract class AbstractAopClass : IApoClass
{
public abstract void SomeAbstractAopMethod(string whatthe);
public virtual void SomeVirtualAopMethod(string abstractparam)
{
//essentiall do nothing
return;
}
}
public class NonAbstractAopMethod : AbstractAopClass
{
public override void SomeAbstractAopMethod(string whatthe)
{
Console.Write("I am the only enforced method");
}
}

容器:

            container.AddNewExtension<Interception>();
//container.Configure<Interception>().SetInterceptorFor<IFrameworkInterceptionTest>(new InterfaceInterceptor());
container.Configure<Interception>().SetInterceptorFor<IApoClass>(new InterfaceInterceptor());

调用代码:

        //resolve it despite it not having and definition, but we've wired the container for the interface implemented by the abstract parent class
var nonabstractmethod = DependencyResolver.Current.GetService<NonAbstractAopMethod>();
nonabstractmethod.SomeAbstractAopMethod("doubt this works");
nonabstractmethod.SomeVirtualAopMethod("if the above didn't then why try");

最佳答案

您的假设是正确的:如果您希望使用拦截,则需要通过容器解析对象,以便 Unity 可以创建代理对象或返回派生类型。

Unity Interception Techniques很好地解释了它的工作原理。

如果我没理解错的话,你想对接口(interface)方法进行拦截,同时尽量减少对现有系统的改动。

您应该能够连接拦截。首先注册接口(interface)和要映射到的具体类型,然后设置拦截:

IUnityContainer container = new UnityContainer();

container.AddNewExtension<Interception>();

container.RegisterType<IApoClass, NonAbstractAopMethod>()
.Configure<Interception>()
.SetInterceptorFor<IApoClass>(new InterfaceInterceptor());

DependencyResolver.SetResolver(new UnityServiceLocator(container));

var nonabstractmethod = DependencyResolver.Current.GetService<IApoClass>();
nonabstractmethod.SomeAbstractAopMethod("doubt this works");
nonabstractmethod.SomeVirtualAopMethod("if the above didn't then why try");

如果您需要将接口(interface)映射到多个具体类型,您可以使用名称来实现:

container.RegisterType<IApoClass, NonAbstractAopMethod2>(
typeof(NonAbstractAopMethod2).Name)
.Configure<Interception>()
.SetInterceptorFor<IApoClass>(
typeof(NonAbstractAopMethod2).Name,
new InterfaceInterceptor()
);

关于c# - AOP、Unity、方法的拦截,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8085631/

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