4

I want to introduce DI to our application.

In our application, we have some generic parameters that are passed through the entire application, mostly via constructor parameters. For example the parameter region limits all actions to a geographic region. This parameter is gathered from user input at runtime and thereby not known at the composition root.

How should I create classes that are always limited to work on one region?

I know that I could use the factory pattern. In this case I would need to pass the DIC into the factory, which is (as far as I know) an anti-pattern.

user3246431
  • 922
  • 1
  • 7
  • 12

1 Answers1

4

The factory pattern is certainly NOT an anti-pattern when working with DI, even though you will see the number of factories decrease when you apply DI correctly.

Still in your situation a factory might not be the best approach. Typically you should prevent letting the object graph depend on runtime data and you should separate the need for that request specific data from the composition of your services.

In your case it would probably be easy to have some sort of IRegionContext or IRegionManager abstraction that allows to to get the region for the current request. This IRegionContext itself is a service, but contains a method that can be called by the application after the object graph is contructed:

public interface IRegionContext
{
    Region CurrentRegion { get; }
}

Application types can depend on the IRegionContext and in the composition root of your web application you can have a special AspNetRegionContext implementation that allows retrieving the region based on the current request.

Steven
  • 166,672
  • 24
  • 332
  • 435
  • Just for clarification: by anti-pattern I meant [passing the container into the factory](http://stackoverflow.com/questions/2539895/dependency-injection-how-to-pass-the-injection-container-around), not the factory itself – user3246431 Jun 19 '14 at 13:22
  • @user3246431: That's true. That's called the [Service Locator anti-pattern](http://blog.ploeh.dk/2010/02/03/ServiceLocatorisanAnti-Pattern/), but you can still do factories, and the factory implementation can call the container without any problem, as long as that implementation is placed inside the Composition Root. – Steven Jun 19 '14 at 14:09