Unity Interception

  • 371
  • 0

最近找了一下 Unity 的 Interception 的解決方案,結果找到了 Unity.Interception。

用法不算難,

首先需要先設定 Interception extension

container.AddNewExtension<Interception>();

接下來為type設定Interceptor以及Behavior

container.RegisterType<ITenantStore, TenantStore>(
  new Interceptor<InterfaceInterceptor>(),
  new InterceptionBehavior<LoggingInterceptionBehavior>(),
  new InterceptionBehavior<CachingInterceptionBehavior>());

這樣當呼叫方法的過程中,就可以進行自己想要的處理。

不過從 sample 中看起來似乎每個型別都得這樣做設定,感覺有點麻煩,

預期想要做到每個想要 Interception 的物件,都預設載入想要處理的行為,

為了做到這樣子的需求,參考了些文章,做一個Extension

class InterceptionExtension : UnityContainerExtension
{
	protected override void Initialize()
	{
		this.Container.AddNewExtension<Interception>();

		this.Context.Registering += Context_Registering;
	}

	private void Context_Registering(object sender, RegisterEventArgs e)
	{
		var interceptor = new Interceptor<InterfaceInterceptor>();
		interceptor.AddPolicies(e.TypeFrom, e.TypeTo, e.Name, this.Context.Policies);

		var behavior = new InterceptionBehavior<LogBehavior>();
		behavior.AddPolicies(e.TypeFrom, e.TypeTo, e.Name, this.Context.Policies);
	}
}

這個 extension 處理 unity 註冊每個 interface 時,就預設載入Interceptor 及 behavior,

這樣就可以在設計主要程式的時候不需要去在意其他需要處理的事,而且不會有忘記的問題,因為都由 container 來進行 config。

config 的程式會像這樣

var container = new UnityContainer();
container.AddNewExtension<InterceptionExtension>();

container.RegisterType<IUserService, UserService>();

參考文章:

https://msdn.microsoft.com/en-us/library/dn178466(v=pandp.30).aspx

http://stackoverflow.com/questions/11909117/use-unity-to-intercept-all-calls-to-imyinterface-somemethod

Sample:

https://github.com/PhoenixChen2016/UnityInterceptionSample