实施 .Net DI 编译时代理?

Implementing .Net DI Compile Time Proxies?

我并不是在寻求具体的实施方式,而是在努力找出适合我所做的事情的术语,以便我可以正确地研究该主题。

我有一堆接口,这些接口是由控制器、存储库、服务等等实现的。在应用程序启动过程中的某个地方,我们使用 Castle.MicroKernel.Registration.Component class 来注册 classes 以用于特定接口。例如:

Component.For<IPaginationService>().ImplementedBy<PaginationService>().LifeStyle.Transient

最近我开始对创建每个 class 和方法调用的审计跟踪感兴趣。这些 classes 有数百个,因此为每个手动编写代理 class 不是很实用。我可以使用模板来生成代码,但我不想用这些来破坏我们的代码库。

所以我很好奇是否有某种即时解决方案。我知道 nHibernate 在某个点创建代理 classes,覆盖所有实体 classes。有人可以指导我如何在这里做类似的事情吗?

类似于:

Component.For<IPaginationService>().ImplementedBy<ProxyFor<PaginationService>>().LifeStyle.Transient

显然这行不通,因为我只能使用泛型来概括方法的类型,而不是方法本身。我可以使用一些棘手的反射方法来做到这一点吗?

您正在寻找 Castle Windsor 所谓的拦截器。这是一个 aspect-oriented way to tackle cross-cutting concerns -- auditing is certainly one of them. See documentation, or an article about the approach:

Aspect oriented programming is an approach that effectively “injects” pieces of code before or after an existing operation. This works by defining an Inteceptor wrapping the logic being invoked then registering it to run whenever a particular set/sub-set of methods are called.

如果您想将其应用于许多已注册服务,请阅读有关 interceptor selection mechanisms: IModelInterceptorsSelector 帮助的更多信息。

使用 PostSharp, things like this can be even done at compile time. This can speed the resulting application, but when used correctly, interceptors are not slow.