dotnetcore/AspectCore-Framework

WebApi架構下Controller跟Service放置不同專案時如何使用?

Closed this issue · 1 comments

我在實作時遇到一些問題想請教一下,
目前程式是使用webapi的架構想加上AOP的框架,
但是我們的controller跟service放在不同的專案底下,
程式架構如下:
solution/
|-- CoreProject/ (控制器项目)
| |-- Controllers/
| | |-- WeatherForecastController.cs
| |-- Program.cs
| |-- CoreProject.csproj
|
|-- CoreServiceProject/ (服务项目)
| |-- Services/
| | |-- WeatherForecastService.cs
| |-- CoreServiceProject.csproj
|
|-- CoreSolution.sln

當程式架構為這樣是時,我在controller的專案寫的LogInterceptor,
不管是用全域或單一呼叫,都無法使用,想請問該如何解呢?
懇請不吝指教,謝謝。

Controller这边,无法直接在action上使用拦截器等标签,一般也不建议这么做,如果有强烈意愿可参考文档,大体上需要先配置AddControllersAsServices(),后将对应action改为虚函数(很久以前测试过,忘记了具体步骤)。
在服务层那边,可以正常使用AOP,可使用自动和手动标签两种形式,以下参考:
//自动事务注入 builder.RegisterDynamicProxy(config => { //为指定程序集的指定名称开头的方法添加自动事务拦截器 var methodNamePatter = new string[] { "GetOrCreate*", "Add*", "Create*", "Save*", "Update*", "Delete*" }; config.Interceptors.AddTyped<TransactionAttribute>(method => { if (method.DeclaringType != null && method.DeclaringType.Namespace.Matches(assembly)) { foreach (var patter in methodNamePatter) { if (method.Name.Matches(patter)) { return true; } } } return false; }); });