jeudi 24 septembre 2015

WCF Service Dependency Injection and Static Factory

I have a service that needs to return a code each time method GetNext() is called. For that, I have several code providers implementing an interface. The same code provider should be used between ServiceHost opening and closing, and so for each service call. I would like to avoid creating one instance of the code provider at each call.

I already looked at several posts, in particular dependency injection for WCF services (mostly Mark Seemann's answers), where solutions using IInstanceProvider and ServiceHostFactory allow to pass parameters during service construction. Perhaps I did not fully understood what was happening there, as I have no extended knowledge of WCF. I ended up implementing a static factory and using it in the service implementation as follows:

[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Single,
                 InstanceContextMode = InstanceContextMode.PerCall)]
public class CodeService : ICodeService
{
    public string GetNext()
    {
        return CodeProviderFactory.GetCodeProvider().GetNextCode();
    }
}

If needed, I could extend this by passing the type of code required to the factory, getting it from configuration DB or file, but that is not the point. Is this the best way to have one single instance of the code provider, and if not, what would be the correct (i.e. more elegant, performant and maintainable) solution? Also is the concern of having a single instance of the code provider legitimate?

Aucun commentaire:

Enregistrer un commentaire