Dependency injection and factory

Posted by legenden on Stack Overflow See other posts from Stack Overflow or by legenden
Published on 2010-06-10T12:15:32Z Indexed on 2010/06/10 13:12 UTC
Read the original article Hit count: 360

Trying to figure out how to best handle the following scenario:

Assume a RequestContext class which has a dependency to an external service, such as:

public class RequestContext : IRequestContext
{
    private readonly ServiceFactory<IWeatherService> _weatherService;

    public RequestContext(ServiceFactory<IWeatherService> weatherService, UserLocation location, string query)
    {
       _weatherService = weatherService;
       ...

What sort of dependency should I require in the class that will ultimately instantiate RequestContext? It could be ServiceFactory<IWeatherService>, but that doesn't seem right, or I could create an IRequestContextFactory for it along the lines of:

public class RequestContextFactory : IRequestContextFactory
{
    private readonly ServiceFactory<IWeatherService> _weatherService;

    public RequestContextFactory(ServiceFactory<IWeatherService> weatherService)
    {
        _weatherService = weatherService;
    }

    public RequestContext Create(UserLocation location, string query)
    {
        return new RequestContext(_weatherService, location, query);
    }
}

And then pass the IRequestContextFactory through constructor injection.

This seems like a good way to do it, but the problem with this approach is that I think it hinders discoverability (devs must know about the factory and implement it, which is not really apparent).

Is there a better/more discoverable way that I'm missing?

© Stack Overflow or respective owner

Related posts about c#

Related posts about dependency-injection