通過fsharp 使用Enterprise Library Unity 2,fsharpunity
接著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 TenantStoreFrom the logging interceptor: "Method Void Msg() returned at 11:59:00"
如果我們反覆調用RegisterType多次,記錄的條目也會相應增多。應該可以想象結構上的變化。
以上。
什是Enterprise Library
我認為百科比較詳細了
baike.baidu.com/view/1542903.htm
Enterprise Library 20 !!!各位大哥大姐了
mircrosoft : www.microsoft.com/...06.exe