我使用一个HadlerAttribute和一个ICallHandler实例让Unity interception正常工作。要让它正常工作,我所要做的就是用Trace属性来装饰这个类,并且拦截器工作得很好。
[Trace]
public interface IPersonService
{
string GetPerson();
}
但是,我希望在几个程序集中对我的所有方法都能进行拦截。所以我使用Unity AutoRegistration来设置我的容器,如下所示:
private static IUnityContainer BuildUnityContainer()
{
var container = new UnityContainer();
//container.AddNewExtension<UnityInterfaceInterceptionRegisterer>();
container.
ConfigureAutoRegistration().
ExcludeSystemAssemblies().
LoadAssemblyFrom(typeof(PersonService).Assembly.Location).
Include(If.ImplementsITypeName, Then.Register()).
ApplyAutoRegistration();
return container;
}
工作得很好,除非我尝试按照这篇文章设置全局注册:http://unity.codeplex.com/discussions/281022
我有一个如下配置的UnityContainerExtension,其中MVC4Unity是我的DLL:
public class UnityInterfaceInterceptionRegisterer : UnityContainerExtension
{
protected override void Initialize()
{
base.Container.AddNewExtension<Interception>();
base.Container.Configure<Interception>().
AddPolicy("LoggingPolicy").
AddMatchingRule<AssemblyMatchingRule>
(new InjectionConstructor("MVC4Unity")).
AddCallHandler(new TraceCallHandler());
base.Context.Registering += new EventHandler<RegisterEventArgs>(this.OnRegister);
}
private void OnRegister(object sender, RegisterEventArgs e)
{
IUnityContainer container = sender as IUnityContainer;
if (e != null && e.TypeFrom != null && e.TypeFrom.IsInterface)
{
container.Configure<Interception>()
.SetInterceptorFor(e.TypeFrom, e.Name, new InterfaceInterceptor());
}
}
}
不幸的是,它总是抛出一个StackOverflowException (!)当它进入OnRegister方法时。
那么问题是,是否有人使用Unity实现了程序集甚至命名空间范围的拦截,这是可行的方法吗?
编辑
似乎无论我在下面的AddMatchingRule行中添加什么,OnRegister处理程序也会为所有包含的程序集调用!(例如,甚至Microsoft.*命名空间程序集!)
base.Container.AddNewExtension<Interception>();
base.Container.Configure<Interception>().
AddPolicy("LoggingPolicy").
// see what other types of matchings rules there are!
AddMatchingRule<NamespaceMatchingRule>
(new InjectionConstructor("MVC4Unity.*")).
AddCallHandler(new TraceCallHandler());
base.Context.Registering += new EventHandler<RegisterEventArgs>(this.OnRegister);
发布于 2013-08-02 07:33:12
我的答案来晚了,但也许有人会发现这很有用。
AssemblyMatchingRule
(MSDN)。container.Configure() .AddPolicy(“NamespaceMatchingRule
.”) .AddMatchingRule( new InjectionConstructor(“InjectionParameter”) .AddCallHandler( new ContainerControlledLifetimeManager(),new InjectionConstructor(),new InjectionProperty(" order ",1));最后一段代码中的
MVC4Unity
名称空间有关更多信息,请查看此链接- Policy Injection MSDN
https://stackoverflow.com/questions/13803656
复制相似问题