【发布时间】:2020-10-06 19:42:10
【问题描述】:
我正在设计一个具有 AOP 架构(postsharp)的程序,它将拦截所有方法调用,但我需要一种将类附加到每个调用的方法。问题是我不想在每个方法调用中都显式地传递类。那么有没有办法将一个类附加到 C# 中的方法调用上?
例如,在 Angular 中,我可以使用自定义拦截器将我想要的任何内容附加到每个传出呼叫的标头。这节省了重复代码。 C#中有这样的东西吗?
@Injectable()
export class CustomInterceptor implements HttpInterceptor {
constructor() { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
request = request.clone({ withCredentials: true });
return next.handle(request);
}
}
这是我的 C# 界面
public class Wrapper: IMyInterface
{
private IMyInterface_wrapped;
public Wrapper(IMyInterface caller)
{
_wrapped = caller;
}
public FOO GetUserStuff(string userName)
{
return _wrapped.GetUserStuff(req);
}
}
}
有没有办法可以像这样调用接口
var wrapper = new Wrapper(new MyInterface());
LoginRequest req = new LoginRequest <------ this needs to be attached to every single method call
{
ClientId = "ABCDEFG",
ClientSecret = "123456"
};
wrapper.GetUserStuff("Username", req); <------- My interface only takes one argument.
wrapper.GetUserStuff("UserName").append(req) <----of course this doesn't work either
有没有一种方法可以调用接口方法并将对象附加到它而无需在接口中实际实现它?
【问题讨论】:
-
如果
Wrapper类型类也接受所需的对象实例作为 ctor 参数,这似乎是依赖注入模式可以解决的问题。 -
我想问一下你的界面。 Wrapper 实现了 MyInterface 并且还在其构造函数中采用了 MyInterface 类型参数,这似乎有点奇怪。这是你打算写这个类的方式吗?此外,是否可以将 req 对象作为参数提供给包装器并按原样调用其他方法? MyInterface myInterface= new Wrapper(req); wrapper.GetUserStuff("用户名");
-
@AntiqTech 的原因是因为这是 AOP,所以 postsharp 将拦截方法调用。我只需要将它暴露出来,以便 postsharp 可以看到该对象。目前 postsharp 只能将用户名视为参数。
-
@TerranceJackson 所以我认为 postsharp 只能看到用户名参数,因为 MyInterface 有 GetUserStuff(string userName)。那么 MyInterface 有“append”方法吗?我在这里盲目射击,但也许你可以将它添加到你的界面,让 Wrapper 类实现它,然后你可以调用 wrapper.append(req) 和 wrapper.GetUserStuff("Username", req);抱歉,如果这完全不合时宜。
-
那么,如果我理解正确的话,每次调用
GetUserStuff方法时,您希望LoginRequest对象作为参数附加到GetUserStuff方法吗?