如何为继承标记界面的接口注册拦截注入?
-
12-12-2019 - |
题
例如,我想调用以下代码来注册一组我想要注入策略的整套服务:
container
.AddNewExtensionIfNotPresent<Interception>().Configure<Interception>().SetDefaultInterceptorFor<IBusinessService>(new InterfaceInterceptor());
.
其中:
ISomeServiceA : IBusinessService
ISomeServiceB : IBusinessService etc
.
我想我读到你 cract 从Isomeservcex到imarkerInterface的某处.... 可以确认。
解决方案
简而言之,查看已加载的组件(如果需要,添加额外的过滤 - 如果在引导程序上完成,则不会缓存)添加默认的拦截器,用于实现指定标记接口的类型。
container.AddNewExtensionIfNotPresent<Interception>();
Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
foreach (Assembly assembly in assemblies)
{
Type[] types = assembly.GetTypes().Where(x => x.IsClass && typeof(T).IsAssignableFrom(x) && x.GetType() != typeof(T)).ToArray();
foreach (Type t in types)
{
container.Configure<Interception>().SetDefaultInterceptorFor(t, new VirtualMethodInterceptor());
}
}
.
编辑:
上面可以使用流畅的API完成,表示我们没有对AppDomain.CurrentDomain.getAssemblies()的naiive依赖关系()(其中不包含在Fluent API Config 中应用的过滤
.Include(If.Implements<IBusinessService>, (x, y) =>
{
if (x.IsClass)
y.Configure<Interception>().
SetDefaultInterceptorFor(x,
new VirtualMethodInterceptor
());
})
. 不隶属于 StackOverflow