Dependency Injection and Factory

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?

+6
c # dependency-injection factory-pattern
source share
2 answers

The beauty of loose communication is that we can constantly hide previous details .

From the IRequestContext consumer perspective, the existence of RequestContext and its dependencies are pure implementation details . Due to the Liskov Substitution Principle, a consumer should only deal with an IRequestContext:

 public class MyClass { private readonly IRequestContext reqCtx; public MyClass(IRequestContext reqCtx) { if (reqCtx == null) { throw new ArgumentNullException("reqCtx"); } this.reqCtx = reqCtx; } // Implement using this.reqCtx... } 

Only in the Root composition application do you finally need to connect everything together. Here's a sketch of a poor person's approach:

 ServiceFactory<IWeatherService> weatherService = new ServiceFactory<IWeatherService>(); UserLocation location = new UserLocation; string query = "foo"; IRequestContext reqCtx = new RequestContext(weatherService, location, query); var mc = new MyClass(reqCtx); 
+5
source share

The Factory pattern is a well-known, documented, and used method. If you are worried that other developers were not up to date, add a link to the wikipedia Factory template page in (xml) in the code.

Also, make sure you name your factories coherently - Microsoft seems to like the provider suffix.

0
source share

All Articles