I am new to dependency injection, but I am happy with Ninject and Ninject.Extensions.Logging to [Inject] my ILogger wherever I need it.
However, some DelegatingHandlers spoil all the fun.
public class HttpsHandler : DelegatingHandler { [Inject] public ILogger Logger { get; set; } protected override Task<HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken cancellationToken) { if (!string.Equals(request.RequestUri.Scheme, "https", StringComparison.OrdinalIgnoreCase)) { Logger.Info(String.Format("{0}: is using HTTP", request.RemoteAddress()); return Task.Factory.StartNew( () => new HttpResponseMessage(HttpStatusCode.BadRequest) { Content = new StringContent("HTTPS Required") }); } return base.SendAsync(request, cancellationToken); } }
Can someone point me in the right direction how to insert Ninject.Extensions.Logger.Nlog2 into Ilogger inside the delegating manipulators?
Update
I think Pete led me in the right direction in the comments (thanks!). I added the following constructor to the HttpsHandler :
public HttpsHandler() { var kernel = new StandardKernel(); var logfactory = kernel.Get<ILoggerFactory>(); this.Logger = logfactory.GetCurrentClassLogger(); }
and now I have Logger running!
All that remains is my question: is this the right way to do this, or is it an anti-pattern?
source share