Trying to figure out how best to deal with the following scenario:
Suppose the RequestContext class is dependent on an external service, for example:
public class RequestContext : IRequestContext { private readonly ServiceFactory<IWeatherService> _weatherService; public RequestContext(ServiceFactory<IWeatherService> weatherService, UserLocation location, string query) { _weatherService = weatherService; ...
What kind of dependency should I require in a class that will eventually create an instance of RequestContext ? It may be ServiceFactory<IWeatherService> , but it does not seem correct, or I could create an IRequestContextFactory for it line by line:
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 the injection constructor.
This seems like a good way to do this, but the problem with this approach is that I believe this is preventing detection (developers should be aware of the factory and implement it, which is not really obvious).
Is there a better / more affordable way that I am missing?
c # dependency-injection factory-pattern
andreialecu
source share