拦截器可以有依赖关系
拦截器像 Windsor 中的常规组件一样注册。与其他组件一样,它们可以依赖于其他组件。
使用以下服务验证凭据:
public interface ICredentialsVerifier
{
bool IsAuthorizedForService(NetworkCredential credentials);
}
public class MockCredentialsVerifier : ICredentialsVerifier
{
public bool IsAuthorizedForService(NetworkCredential credentials)
=> credentials.UserName == "tom" && credentials.Password == "pass123";
// this ^ verification is obviously silly, never do real security like this
}
我们可以使用以下拦截器:
public class AuthorizationInterceptor : IInterceptor
{
private readonly ICredentialsVerifier _credentialsVerifier;
public AuthorizationInterceptor(ICredentialsVerifier credentialsVerifier)
{
_credentialsVerifier = credentialsVerifier;
}
public void Intercept(IInvocation invocation)
{
var userCredentials = invocation.Arguments[0] as NetworkCredential;
if (_credentialsVerifier.IsAuthorizedForService(userCredentials))
{
invocation.Proceed();
}
else
{
invocation.ReturnValue = $"User '{userCredentials.UserName}' was not authenticated.";
}
}
}
我们只需要在组合根中正确注册它,如下所示:
var container = new WindsorContainer();
container.Register(
Component.For<AuthorizationInterceptor>(),
Component.For<ICredentialsVerifier>().ImplementedBy<MockCredentialsVerifier>(),
Component.For<IService>().ImplementedBy<Service>().Interceptors<AuthorizationInterceptor>());
var service = container.Resolve<IService>();