通过fsharp 使用Enterprise Library Unity 2

接着Depandency Injection继续。

最想做的还是用现成的程序模块对程序进行行为注入。只是不急,在此之前自己写一个接口对象观察一下IInterceptionBehavior接口的功效。

type LogingInterceptionBehavior() = 
    let WriteLog message = 
        printfn "From the logging interceptor: %A" message
    interface IInterceptionBehavior with
        member x.Invoke((input:IMethodInvocation), (getNext:GetNextInterceptionBehaviorDelegate)) = 
            String.Format("Invoke method {0}:{2} at {1}", input.MethodBase, DateTime.Now.ToLongTimeString(), input.Target) |>  WriteLog
            let result = getNext.Invoke().Invoke(input, getNext)
            match result.Exception with
            | null ->
                String.Format("Method {0}:{3} returned {1} at {2}", input.MethodBase, result.ReturnValue, DateTime.Now.ToLongTimeString(), input.target) |> WriteLog
            | _ ->
                String.Format("Method {0} threw exception {1} at {2}", input.MethodBase, result.Exception.Message, DateTime.Now.ToLongTimeString()) |> WriteLog
            result
        member x.GetRequiredInterfaces() =
            Type.EmptyTypes |> Seq.ofArray
        member x.WillExecute with get() = true

记录日志是最常见的行为注入。

这里最重要的是实现IIntercptionBehavior接口中的Invoke方法,这种方法有两个參数。第一个是被拦截的接口,第二个则是一个托付行为列表(以托付的形式给出)。

这里我们在列表循环前记录參数,在循环后记录返回值。


let result = getNext.Invoke().Invoke(input, getNext)
这句代码完毕详细的工作。

拦截的行为是依次进行的,彼此之际并无联系,也不应有联系。每一个拦截都仅关注本身的详细行为。这是最好的情况,只是实际中也并不能保证这一点。对拦截的顺序还是要多加注意。比方缓冲的样例,有可能截断注入行为列表。每一个行为对兴许的动作不可控,所以当缓冲须要做一些特殊操作直接返回值时,会忽略兴许的动作。又比方权限管理。


以下进行注冊,管理容器须要支持Interception

container.AddNewExtension<Interception>() |> ignore

注冊
container.RegisterType<ITenantStore, TenantStore>(new Interceptor<TransparentProxyInterceptor>(), 
                                                  new InterceptionBehavior<LogingInterceptionBehavior>())

let t = container.Resolve<ITenantStore>();
t.Msg()
能够看到当解析接口时就会跳出非常多记录。猜想应该在构造对象时做了不少的动作,父类的接口调用也会被记录。
最后是结果
From the logging interceptor: "Invoke method Void Msg():FSI_0002+TenantStore at 11:59:00"
Hello, it's TenantStore
From the logging interceptor: "Method Void Msg() returned  at 11:59:00"

假设我们重复调用RegisterType多次。记录的条目也会对应增多。应该能够想象结构上的变化。


以上。



原文地址:https://www.cnblogs.com/gccbuaa/p/7373434.html