我有一个web api 2 applicationn使用woin进行自托管和ninject进行依赖注入。我试图在扩展AuthorizationFilterAttribute的类中注入一个依赖项。我无法让它成功运作。
Startup.cs
public class Startup {
// This code configures Web API. The Startup class is specified as a type
// parameter in the WebApp.Start method.
public void Configuration(IAppBuilder appBuilder) {
HttpConfiguration config = new HttpConfiguration();
IKernel kernel = CreateKernel();
config.Filters.Add(new AuthorizationFilter(kernel.Get<IAuthenticator>()));
config.MapHttpAttributeRoutes();
appBuilder.UseNinjectMiddleware(() => kernel).UseNinjectWebApi(config);
}
private static StandardKernel CreateKernel() {
var kernel = new StandardKernel();
kernel.Load(Assembly.GetExecutingAssembly());
kernel.Bind<IAuthenticator>().To<AuthServiceAuthenticator>().InSingletonScope()
.WithConstructorArgument(new {
authServiceUrl = @"http://authservice/"
});
return kernel;
}
}
AuthorizationFilter.cs
class AuthorizationFilter : AuthorizationFilterAttribute {
private const string AUTH_TOKEN_HEADER_KEY = "Session-Id";
private IAuthenticator _authenticator;
public AuthorizationFilter(IAuthenticator authenticator) {
_authenticator = authenticator;
}
public override void OnAuthorization(HttpActionContext filterContext) {
IEnumerable<string> authToken;
AuthResponse validateResponse = null;
if (filterContext.Request.Headers.TryGetValues(AUTH_TOKEN_HEADER_KEY, out authToken)) {
bool isAuthorized = _authenticator.ValidateAuthToken(authToken.First(), out validateResponse);
}
base.OnAuthorization(filterContext);
}
}
AuthServiceAuthenticator.cs
class AuthServiceAuthenticator : IAuthenticator {
private const string VALIDATE_PATH = "validate?value=";
private const string CLIENT_NAME_HEADER = "X-Client-Name";
public Uri _authServiceUrl;
public AuthServiceAuthenticator(Uri authServiceUrl) {
_authServiceUrl = authServiceUrl;
}
private Uri BuildValidateUrl(string authToken) {
string path = VALIDATE_PATH + authToken;
return new Uri(_authServiceUrl, path);
}
public bool ValidateAuthToken(string authToken, out AuthResponse authResponse) {
Uri validateUrl = BuildValidateUrl(authToken);
WebRequest webRequest = HttpWebRequest.Create(validateUrl);
using (WebResponse response = webRequest.GetResponse()) {
try {
using (Stream stream = response.GetResponseStream()) {
using (StreamReader reader = new StreamReader(stream)) {
string responseBody = reader.ReadToEnd();
authResponse = JsonConvert.DeserializeObject<AuthResponse>(responseBody);
}
}
} finally {
response.Close();
}
}
return authResponse?.Success ?? false;
}
}
这是我得到的错误
Error activating Uri using implicit self-binding of Uri
A cyclical dependency was detected between the constructors of two
services.
Activation path:
3) Injection of dependency Uri into parameter baseUri of constructor of
type Uri
2) Injection of dependency Uri into parameter authServiceUrl of
constructor of type AuthServiceAuthenticator
1) Request for IAuthenticator