我正在设计一个具有 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);
}
}
Run Code Online (Sandbox Code Playgroud)
这是我在 C# 中的界面
public class Wrapper: IMyInterface
{
private IMyInterface_wrapped;
public Wrapper(IMyInterface caller)
{
_wrapped = caller;
}
public FOO GetUserStuff(string userName)
{
return _wrapped.GetUserStuff(req);
}
}
}
Run Code Online (Sandbox Code Playgroud)
有没有办法像这样调用接口
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
Run Code Online (Sandbox Code Playgroud)
有没有一种方法可以调用接口方法并将对象附加到它,而无需在接口中实际实现它?
基本上你想要的是 - 每当wrapper.GetUserStuff调用该方法时,类对象LoginRequest就可以使用一个对象Wrapper。
ClientId但正如您在评论部分中回答的那样,和的值ClientSecret不会改变。LoginRequest然后,您可以通过简单地在类内部创建对象来避免每次在外部创建对象并将其作为方法参数传递到LoginRequest内部的整个麻烦Wrapper-
public class Wrapper : IMyInterface
{
private IMyInterface _wrapped;
private LoginRequest _req;
public Wrapper(IMyInterface caller)
{
_wrapped = caller;
_req = new LoginRequest { ClientId = "ABCDEFG", ClientSecret = "123456" };
}
public int GetUserStuff(string userName)
{
return _wrapped.GetUserStuff(_req);
}
}
Run Code Online (Sandbox Code Playgroud)
通常,您会将ClientId和ClientSecret值存储在其他地方(而不是对它们进行硬编码)并相应地读取它们。
而且,如果您无法LoginRequest从类访问该类Wrapper(可能是在没有所需程序集引用的单独层/项目上),那么您可以声明一个类ClientInfo并像这样使用它 -
public class ClientInfo
{
public string UserName { get; set; }
public string ClientId { get; set; }
public string ClientSecret { get; set; }
}
public class Wrapper : IMyInterface
{
private IMyInterface _wrapped;
private ClientInfo _info;
public Wrapper(IMyInterface caller)
{
_wrapped = caller;
_info = new ClientInfo { ClientId = "ABCDEFG", ClientSecret = "123456" };
}
public int GetUserStuff(string userName)
{
_info.UserName = userName;
return _wrapped.GetUserStuff(_info);
}
}
Run Code Online (Sandbox Code Playgroud)
然后可以根据传递给它的对象caller创建对象。LoginRequestClientInfo
| 归档时间: |
|
| 查看次数: |
250 次 |
| 最近记录: |