攔截器可以有依賴關係

攔截器像 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>();