What effect does IgnoreStructureMapAttributes() method have on the assembly scanner?
The documentation for IgnoreStructureMapAttributes is sparse and doesn't state what effect the method has.
As I see it, this could have two possible effects
all types are registered, not just those with the StructureMap attributes.
all types are ignored.
Related
I am bit new to dependency injection & came across subjected question while working.
Lets say I have a class 'Employee' which has one method this method say 'Promote' gets conditionally called that too on rarest scenario.
'Promote' method uses an object of 'ValueAddition', now is it best practice to have this objected injected via constructor & user global object or should I
resolve the dependency in method itself?
What is recommended best practice? or any pointer on the life time of resolved dependency would be helpful.
In general you should always look to inject dependencies rather than use service location (ie, resolving a dependency directly from the inversion of control container). There's a great, pretty well known blog article here called "Service Locator is an Anti-Pattern" that can help clarify the reasons.
You may run into other issues as you expand that seem to point you to using service location. In general, you really should design around those issues instead of falling back to service location.
I only need the object in one method. Consider moving the functionality of the method to a different object. For example, maybe the Promote() method should be on an IEmployeePromoter where you resolve that and it takes the special object. Then you'd call Promote(Employee) and pass in the employee rather than changing the dependencies for an Employee. Sometimes your inversion of control container will have a way to generate a factory (like Func<T> or Lazy<T>) to help you defer resolution until you actually need it.
I have way too many dependencies. Usually this means your object is doing too much. The single responsibility principle can help you refactor your objects to be a more manageable size. Smaller objects generally need fewer dependencies because they have far fewer concerns to manage.
There's a good amount of documentation and books out there on the pattern of dependency injection. It might be good to widen the scope of your search to looking at the patterns and practices in general when not applied to a particular framework (or even language) and it can help inform you of best practices in your own code.
When should I use property injection?
Should I use by default constructor injection if instance creation in fully controlled?
Am I right that using a constructor injection I write container-agnostic code?
When should I use property injection?
You should use property injection in case the dependency is truly optional, when you have a Local Default, or when your object graph contains a cyclic dependency.
Property Injection however causes Temporal Coupling and when writing Line of Business applications, your dependencies should never be optional: you should instead apply the Null Object pattern.
Neither should you use a Local Default, which is:
"A default implementation of an abstraction that's defined in the same assembly as the consumer." [DIPP&P, Section 4.2.2]
Local Defaults should not be used in Line of Business applications, because it complicates testing, hides the dependency, and makes it easy to forget to configure the dependency.
Neither should object graphs have cyclic dependencies. This is an indication of a problem in your application design.
Should I use by default constructor injection if instance creation in fully controlled?
Yes. Constructor injection is the best way. It makes it very easy to see which dependencies a class has, makes it possible to make dependencies required, and prevents Temporal Coupling.
Am I right that using a constructor injection I write container-agnostic code?
This is correct. Constructor injection allows you to delay the decision of which DI library to use, and whether at all you use a DI library.
For a more detailed explanation of the above, and much more, read the book Dependency Injection Principles, Practices, and Pattern (DIPP&P) by Mark Seemann and myself.
The usefulness of property injection is so limited, that while working on the book, Mark and I even discussed labeling Property Injection an anti-pattern. In the end we felt we couldn't make a case that was as strong as, for instance, Ambient Context, which we did decide to describe as an anti-pattern in that edition. The case for Ambient Context was crystal clear, while being much muddier for Property Injection. But this is why, however, we added many warning notes to the Property Injection section (4.4), because we feel strongly Property Injection is not a good solution for the majority of cases.
There are several problems, though, that Property Injection seems to solve at first, such as the problem of Constructor Over-Injection (where a constructor contains many dependencies). Constructor Over-Injection, however, is almost always caused by design deficits, such as:
Class having too many responsibilities
Lack of natural clusters
Choosing inheritance over composition
Application of Cross-Cutting Concerns through base classes instead of Decorators or Interceptors
The accepted answer argues in favor of constructor injection and takes a rather critical stance toward property injection. As such, it does not put focus on addressing the problems that property injection actually solves, if used correctly. Therefore I want to take the opportunity to address some of these points and also to provide some counter arguments to the accepted answer.
When should I use property injection?
Imagine you have a project with 100+ controllers and all those controllers are extending a custom base controller (parent-service). In such a situation, where a service is extended by several child-services, employing constructor injection is a burden: For every constructor you create, you need to relay arguments to your parent-service's constructor. If you decide to extend your parent service's constructor signature you will also be forced to extend the signatures of all child-services' constructors.
To make this example more vivid, say you start your project with a base controller having a parameterless constructor.
Now after a month you decide you want a logger service in your base controller. → Not only will you have to change the base controller constructor's signature but also those of your 100+ child controllers.
Now again after a month you need access to a user service in your base controller → Again, you'll have to change the constructor signature of your 100+ child controllers.
you get the point...
With property injection you can easily circumvent this whole inconvenience by simply adding the necessary properties to your parent service and letting your DI-mechanism handle the injection via reflection. As a side effect, this also greatly reduces the risk of merge conflicts (since the files touched is reduced to a minimum).
So far, I have been talking mostly about controllers but this example counts for any situation in which you have a service hierarchy – the deeper or broader this hierarchy gets, the greater the burden of constructor injection. However, avoiding service-hierarchies altogether may not always be a reasonable choice in a project.
One could say the decision between property and constructor injection is really a decision between a pragmatism and OOP "purism".
From a "purist" OOP perspective, the rule is (as stated in the accepted answer) to initialize all required fields of a class via its constructor in order to avoid granting any access to the newly created instance in an "unfinished" state (which may result in an exception being later thrown).
With reference to this rule, an OOP-purist has a valid point in saying that property injection (temporarily) leaves your services in an "unfinished" state (the timespan between when your constructor has returned and the moment your property is injected) and that this increases the risk that your application may break.
However, when talking about services managed by an IoC/DI container, this risk is practically reduced to zero if you consider that your DI-mechanism is responsible for resolving the dependency graph and wiring everything up before any user-action or api-request actually makes it into your system or needs being processed. For example, at the time a controller's action is invoked you can be sure that your services were properly wired up and injected into your controller's properties (given of course, that you configured them correctly in advance).
Also the argument that it is only possible with constructor injection to make your dependencies "required" is rather weak in a world where you are not responsible for manually injecting services into your classes but delegate this task to your IoC mechanism. Even worse, you may get a false sense of security because you stated via constructor that a ServiceX requires ServiceY – but if you forgot to register your ServiceY with your DI-mechanism, you merely get null injected into your ServiceX's constructor.
Another "argument" against property injection is that it becomes harder for your fellow programmers to distinguish between properties that are managed by the DI mechanism and those which are simply non-DI-related. However, in this case you can just use a marker attribute to "opt-in" for DI or add short comments above your properties to clear things up, when the case is not clear. Also, in a service-class, it is rather unusual to have properties referring to other services that are not supposed to be manged by your DI mechanism.
Finally, as for saying that constructor injection makes unit testing easier (since you know what dependencies are required by a class), I would simply argue, that with property injection you will soon enough notice that you forgot to include a dependency when your tests begin to fail due to a certain service being undefined.
Should I use by default constructor injection if instance creation in fully controlled?
With all the above being said, I think I can answer your second question with: Not necessarily.
It depends on your project's size, the kind of service-hierarchy you employ, how often your parent-services' dependencies change and how much time and resources you are willing to invest in managing parameters and passing arguments up the service-hierarchy.
Am I right that using a constructor injection I write container-agnostic code?
Yes! – Under the premise that you are not injecting the container itself... which you shouldn't! ;)
All the above being said, here are some quotes from Martin Fowler's great discussion on dependency injection directly addressing the question of constructor vs setter/property injection, and I can fully subscribe to the last quote :)
If you have multiple constructors and inheritance, then things can get particularly awkward. In order to initialize everything you have to provide constructors to forward to each superclass constructor, while also adding you own arguments. This can lead to an even bigger explosion of constructors.
Despite the disadvantages my preference is to start with constructor injection, but be ready to switch to setter injection as soon as the problems I've outlined above start to become a problem.
This issue has led to a lot of debate between the various teams who provide dependency injectors as part of their frameworks. However it seems that most people who build these frameworks have realized that it's important to support both mechanisms, even if there's a preference for one of them.
A final remark: If you, for some reason, want to switch back from property injection to constructor injection, no problem, you can always add a constructor with the parameters to be injected and assign the properties via your constructor – dead-simple.
I'm working on an iOS app where we need different binaries for each customer based on their needs. A customer may want to change all the colors, icons and texts. We can do that through white labeling process. The problem here, though, is when they ask for different behavior, for instance, removing login screen and making it optional to login.
I thought we can use dependency injections and use different handlers for each customer if needed. For instance, we can have LoginHandler1 and LoginHandler2, both implementing ILoginHandler and inherit from UIViewController.
However, use of dependency injection is costly, it slows down the app because resolving is expensive comparing to normal instantiation.
The other way is to define all these behaviors in the app and enable/disable them in a plist file. like "is login optional? yes/no"
Any suggestions?
Thanks
You should create the entire object graph up-front, in the composition root. Object creation, and constructor injection, should not take much time at all as long as your constructors are not doing any actual work.
That being said, there are times when creating the entire object graph at the start of the application may take longer than is acceptable. In those cases, you can use lazy-loading to defer the costly initialization until later - while still creating the objects in the composition root.
Mark Seemann describes this approach in more detail here: Compose object graphs with confidence.
I thought we can use dependency injections and use different handlers for each customer if needed.
You thought right. Flexibility is one of the main reasons people use DI.
However, use of dependency injection is costly, it slows down the app because resolving is expensive comparing to normal instantiation.
It really doesn't cost that much at all. Have you tried it yourself? Unless the object in question (i.e. the object being injected) is very expensive to instantiate, you have no real reason to stay away from DI and Inversion Of Control. Also, as #Lilshieste noted above, creating the object graph up front (see AppDelegate) will probably make this even less a problem.
A good way of doing that is described here:
http://cocoapatterns.com/passing-data-between-view-controllers/ and here http://cocoapatterns.com/ios-view-controller-transitions-mediator-pattern/
The other way is to define all these behaviors in the app and enable/disable them in a plist file. like "is login optional? yes/no"
While less "elegant", this solution is a pretty useful one, especially if the project is not really big in terms of number of classes and VCs. It is also the easiest one to implement if the app code is already laid out and introducing major design changes would ask for lots of refactoring.
Always take action based on the task at hand, there is rarely if ever a single solution to a software design problem.
StructureMap defines an interface IBootStrapper, that I see a number of people implementing in their bootstrapper classes.
But I can't find anything that gives some indication as to why you should implement this interface. What does one gain by doing so?
It is simply a convention that allows tooling (like StructureMapDoctor) to discover your bootstrapping code. It is purely optional, and not required by StructureMap itself.
Is it best practise to resolve and inject concrete types at the edge of the domain model and then have these fall down through the domain? For example, having the container inject concrete types into MVC controller constructors in a web app, or service endpoints in a service based app?
My understanding of container object graph wire up is a little ropey.
Is it ever appropriate to do the equivalent of Container.Resolve() within the domain?
DI is really only a means to an end: loose coupling. It is a way to enable loose coupling by injecting interfaces (or base classes) into consumers so that you can vary both independently of each other.
As a general rule, nothing much is gained by injecting a concrete type. You can't swap the type with another type, so the main advantage of DI is lost.
You could argue that this means that you'd just as well just create the concrete instances from within the consumers, but a better alternative is to extract interfaces from those types (and then inject them).
And no: it's never appropriate to pull from the container from within the Domain Model. That is the Service Locator anti-pattern. The Hollywood Principle applies here as well:
Don't call the container; it'll call you
(That said, even with a concrete type there are some secondary benefits from injecting it. If it's non-sealed and has one or more virtual members, you can still override a bit of its behavior, and even if it's sealed, you still get to control its lifetime if you inject it - e.g. you can share the same instance between multiple consumers. However, these benefits are purely secondary and usually not the main reason we decide to inject anything.)
Another question (and the one you seem to be actually asking) is whether it's appropriate to inject services just to be passing them on to other services. No, it's not, since it would violate the Single Responsibility Principle and lead to Constructor Over-Injection.
It's better to wrap fine-grained service in more coarse-grained services. I call these Aggregate Services or Abstract Facades. While these in themselves will have dependencies (like the service endpoints you mention), these will be implementation details. From the point of view of the top-level consumer, they don't exist.
Not only does this nicely solve the issue around too many dependencies in the constructor, it also helps you have better isolation between application layers.
Check out Krzysztof Koźmic's blog post(s) about the subject - I think he has some great opinions about this, and they pretty much sum up what seems to be the current "best practice".