我想在我的应用程序中使用拦截器来进行日志记录。 当然,我可以使用这样的拦截器注册每种类型:
container.AddNewExtension<Interception>();
container.RegisterType<ITenantStore, TenantStore>(
new Interceptor<InterfaceInterceptor>(),
new InterceptionBehavior<LoggingInterceptionBehavior>());
但由于我有很多类型,我想知道是否有更清晰的方法为我的所有课程做到这一点?
答案 0 :(得分:2)
这是一种方法,可以对已经注册的所有类型进行拦截。请在注册完成后再拨打此电话。然后,您可以使用Policy Injection来连接您想要使用的拦截器。
public static class UnityContainerInterceptionExtensions
{
public static IUnityContainer EnableInterceptionForAllRegisteredTypes
(this IUnityContainer unityContainer)
{
unityContainer
.Registrations
.ForEach(r => unityContainer.EnableInterception(r.RegisteredType, r.Name));
return unityContainer;
}
public static IUnityContainer EnableInterception<T>
(this IUnityContainer unityContainer, string name = null)
{
return unityContainer.EnableInterception(typeof (T), name);
}
public static IUnityContainer EnableInterception
(this IUnityContainer unityContainer, Type registrationType, string name = null)
{
// Don't allow interception of unity types
if (registrationType.Namespace.StartsWith(typeof(IUnityContainer).Namespace))
return unityContainer;
// Don't allow interception on the intercepting call handlers
if (typeof (ICallHandler).IsAssignableFrom(registrationType))
return unityContainer;
var interception = unityContainer.Configure<Interception>();
var interfaceInterceptor = new InterfaceInterceptor();
if (interfaceInterceptor.CanIntercept(registrationType))
{
interception
.SetInterceptorFor(registrationType, name, interfaceInterceptor);
return unityContainer;
}
var virtualMethodInterceptor = new VirtualMethodInterceptor();
if (virtualMethodInterceptor.CanIntercept(registrationType))
{
interception
.SetInterceptorFor(registrationType, name, virtualMethodInterceptor);
return unityContainer;
}
var transparentProxyInterceptor = new TransparentProxyInterceptor();
if (transparentProxyInterceptor.CanIntercept(registrationType))
{
interception
.SetInterceptorFor(registrationType, name, transparentProxyInterceptor);
return unityContainer;
}
return unityContainer;
}
}