I'm trying to embed SimpleInjector in my WCF project (I've followed the instructions here). Till now everything went well except from IHttpHandler issue: the current implementation uses IHttpHandler which in turn uses MyServiceWrapper static instance:
public class IsAliveHandler : IHttpHandler
{
private const string SERVER_ERROR = "Bad";
private const string SERVER_OK = "OK";
public void ProcessRequest(HttpContext context)
{
var quoteSucceeded = false;
var isLastLoginSucceeded = MyServiceWrapperContainer.Manager.IsLastLoginSucceeded;
//More logic here ...
}
}
Now, since I moved my application to use the SimpleInjector DI mechanism I can't use such a static access since I want to use the same instance as held by the DI container. constructor injection here gets exception:
[MissingMethodException: Constructor on type '***.Applications.MyServiceWrapperService.KeepAliveHandler.IsAliveHandler' not found.]
Is there a way to use container in such scenario? Are there alternatives?
Generally, I can understand that such problem is smell of using state, but currently this is the requirement.
Your
IsAliveHandlercan't have any constructor arguments (this is a constraint of your application framework).Instead, you should make your
IsAliveHandlera Humble Object and consider it to be part of your Composition Root.This means that you extract all interesting logic out of the
IsAliveHandler(e.g. into anIsAliveService) and changeIsAliveHandlerto something as follows:In other words, the only thing you let the
IsAliveHandlerdo is to request the service from the DI Container and invoke the appropriate method on that resolved service.Do note that
IsAliveHandlershould stay completely stateless: the resolveIsAliveServiceshould nowhere be stored. You should leave it up to the DI Container to provide you with the correct instance.In case this operation runs outside the context of a Simple Injector
Scope, you might to wrap the operation inside such aScope: