我正在尝试在我的接口(或实现)上使用拦截调用处理程序和处理程序属性。假设我的接口有两个方法 DoSomething() 和 DoSomethingElse(),而我只有 DoSomethingElse() 的拦截器;当我解析我的主界面时,调用处理程序的构造函数会被调用,即使我从未调用 DoSomethingElse()。
我通过解析到 Lazy(of IMainInterface) 来尝试这个,但是当我调用函数 DoSomething() 时,调用处理程序仍然是不必要的。有没有办法通过代码或配置来防止这种情况发生。这是我的示例实现
处理程序属性和调用处理程序
<AttributeUsage(AttributeTargets.Method)>
Public Class NormalSampleAttribute
Inherits HandlerAttribute
Public Sub New()
Console.WriteLine("Constructor of Normal Sample Attribute")
End Sub
Public Overrides Function CreateHandler(container As Microsoft.Practices.Unity.IUnityContainer) As Microsoft.Practices.Unity.InterceptionExtension.ICallHandler
Console.WriteLine("Create Handler")
Return New SampleCallHandler
End Function
End Class
Public Class SampleCallHandler
Implements ICallHandler
Public Sub New()
Console.WriteLine("Constructor of Sample Call handler")
End Sub
Public Function Invoke(input As IMethodInvocation, getNext As GetNextHandlerDelegate) As IMethodReturn Implements ICallHandler.Invoke
Console.WriteLine("Invoke of Sample Call handler - " & input.MethodBase.Name)
Return getNext.Invoke(input, getNext)
End Function
Public Property Order As Integer Implements ICallHandler.Order
End Class
接口和实现
Public Interface IMainInterface
Sub DoSomething()
<NormalSample()>
Sub DoSomethingElse()
End Interface
Public Class MainClass
Implements IMainInterface
Public Sub New()
Console.WriteLine("main class - Constructor")
End Sub
Public Sub DoSomething() Implements IMainInterface.DoSomething
Console.WriteLine("main class do something...")
End Sub
Public Sub DoSomethingElse() Implements IMainInterface.DoSomethingElse
Console.WriteLine("main class do something else...")
End Sub
End Class
注册和执行方法的主模块
Module Module1
Public container As IUnityContainer
Sub Main()
container = New UnityContainer
DoRegistrations()
Console.WriteLine("Before lazy Resolve")
Dim lmc As Lazy(Of IMainInterface) = container.Resolve(Of Lazy(Of IMainInterface))()
Console.WriteLine("Before making lazy function call")
lmc.Value.DoSomething()
Console.ReadLine()
End Sub
Sub DoRegistrations()
container.AddNewExtension(Of InterceptionExtension.Interception)()
container.RegisterType(Of IMainInterface, MainClass)()
container.Configure(Of Interception).SetDefaultInterceptorFor(Of IMainInterface)(New InterfaceInterceptor)
End Sub
End Module
它产生以下输出:
在惰性解决
之前 在进行惰性函数调用
主类之前 - 构造
函数 普通样本属性的构造函数
创建处理
程序 样本调用处理程序
主类的构造函数 做一些事情......
尽管 DoSomethingElse() 从未被调用,但处理程序创建的成本被添加到所有流中。有没有办法避免这种情况?任何帮助表示赞赏。
提前致谢!SV