I am designing a program with AOP architecture(postsharp) that will intercept all method calls but I need a way to attach a class to every call. The problem is I don't want to have to pass the class explicitly in every single method call. So is there a way to attach a class to a method call in C#?
For example, In angular I can use a custom interceptor to attach anything I want to a header for every outgoing call. This saves down on repeating code. Is there anything like this in 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);
}
}
This is my interface in C#
public class Wrapper: IMyInterface
{
private IMyInterface_wrapped;
public Wrapper(IMyInterface caller)
{
_wrapped = caller;
}
public FOO GetUserStuff(string userName)
{
return _wrapped.GetUserStuff(req);
}
}
}
Is there a way that I can call the interface like this
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
Is there a way that I can call the interface method and attach the object to it without actually implementing it in the interface?
Wrapper
type classes also accepted the required object instance as a ctor argument. – LuedtkeGetUserStuff
method gets called, you want theLoginRequest
object to be attached as a parameter to thatGetUserStuff
method? – LenorelenoxGetUserStuff
method? – LenorelenoxClientId
andClientSecret
values change for differentGetUserStuff
call? – LenorelenoxAsyncLocal<T>
answer by @ICodeGorilla is what you need since the value stored inAsyncLocal
would be available as long as you flow ExecutionContext correctly (which is not a concern if you are not using some custom threading). – Connatural