我试图在我的接口(或实现)上使用拦截调用处理程序和处理程序属性。让我说我的接口有两个方法DoSomething()和DoSomethingElse(),我只有DoSomethingElse()的拦截器;当我解析我的主界面时,即使我从不调用DoSomethingElse(),也会调用Call Handler的构造函数。
我通过解析为Lazy(IMainInterface)尝试了这个,但是当我调用函数DoSomething()时,仍然会不必要地创建Call Handler。有没有办法通过代码或配置来防止这种情况发生。这是我的示例实现
处理程序属性和呼叫处理程序
<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