Unity Container: Difference between constructor vs property vs method injection - c#

This is specific to Unity DI.
It seems common wisdom states that if the majority of your class requires a certain dependency then you should use constructor injection. If the dependency is only needed in a subset of use cases for the class then you should use property injection (or possibly method injection). I assumed this was because the latter two don't resolve the object until they're referenced, but in my experience all three of these resolve the dependencies on object creation, so what is the utility of using one over the other?
Also, the Unity documentation on deferring object creation only mentions the Lazy<> and Func<> generics.
Is there a way to set up property and/or method injection to defer resolution?
If not, are there different methods just to allow for stylistic preferences?

Ok, basically deferring resolution using properties is a bad practice. Some DI containers (Microsoft.Extensions.* https://learn.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-3.1) does not even allow you to do that.
If your code followed SOLID principles (https://en.wikipedia.org/wiki/SOLID), the need to defer resolution would almost never occur. Instead, you should split your classes into smaller pieces and each would inject through its constructor. If you still need to defer the resolution (e.g., when you create a facade), you can inject an abstract factory and called its factory method to instantiate instance when you need it.

Related

Deciding between restriction and freedom (Interfaces and Dependency Injection)

As I understand it, interfaces in C# can be thought of as a contract or promise that a derived class must follow. This allows different objects to behave in different ways when the an overridden method is called.
DI, how I understand it, offers the ability to reduce dependencies by being able to inject the dependency (usually through a container) though the ctor, property, or method.
It seems like they are 2 completely opposing forces between freedom and restraint. I can create a contract that says a derived class MUST follow these certain guidelines which is restrictive in nature versus DI which allows me to inject dependencies (I know that the dependency has to inherit the interface but still...) which is permissive in nature. I can make everything injectable and wildly and change the class.
I guess my question is what's your process in deciding how restrictive you want to be? When is it more important to use interfaces for polymorphism or DI when you want complete freedom? Where do you draw the line? Is it ok to use interfaces when you want the structure (methods and properties) to align among different derived classes and DI when the parameters can be wildly different?
EDIT:
Maybe DI was the wrong example. Let's say I have an IPlugin and Plugin Factory. All plugins need the same information, work the same, etc. So it would make sense to use an interface. Now, one plugin works the same but needs different parameters or different data but ultimately the same structure i.e. Load, Run, etc.
I wanted to pass a command object that can expose different parameters that the plugin will need (using DI) and then each plugin can use the properties of that command object but the fact that I can inject a command object with wildly different parameters kinda breaks the whole idea of having a contract in the first place. Would that be kosher?
DI, how I understand it, offers the ability to reduce dependencies by being able to inject the dependency (usually through a container) though the ctor, property, or method.
Incorrect. Static code analysis shows the dependency is still there. DI just changes how you ended up with an instance to the object. If your ctor say is expecting objects of a particular class then you have a dependency to that type but you also have strong-coupling to a class which is bad. However if your ctor is expecting types of a certain interface, then you have a dependency to that contract definition but not to the actual implementation (lose coupling).
As I understand it, interfaces in C# can be thought of as a contract or promise that a derived class must follow. This allows different objects to behave in different ways when the an overridden method is called.
Yes, but they are also a way to abstract a component by hiding unnecessary details, something say a class cannot. That's why in reasonably large systems it's nice to have a MyContracts.dll in which you define all your interfaces; and say BusinessLogic.dll and ClientStuff.dll. ClientStuff depends on contracts but it doesn't care about the actual implementation and possible zillions of other dependencies BusinessLogic.dll may have (typical WPF or WCF application say).
When is it more important to use interfaces for polymorphism or DI when you want complete freedom? Where do you draw the line? Is it ok to use interfaces when you want the structure (methods and properties) to align among different derived classes and DI when the parameters can be wildly different?
DI does not offer any more freedom then a non-DI system. However I think you might be a little confused over terminology or concepts. DI is always good. Injecting interfaces over class types is better as I mentioned above.
I can create a contract that says a derived class MUST follow these certain guidelines which is restrictive in nature versus DI which allows me to inject dependencies
A contract is a contract is a contract whether it is in the form of an interface or abstract class. If the constructor (constructor-injection) or property (property injection) is asking for a MyDbConnection then that sets up a requirement as to what can be injected more so than say just expecting a IMyDbConnection.
I think you may have it wrong with regards to what DI does. DI does not always inject classes and interfaces are not just for polymorphism. The latter is a common mistake. DI has nothing to do with being "restrictive". That is up to you as to the type you are expecting to have injected.
In fact expecting a concrete class object or something derived by abstract class to be injected is more "restrictive" than injecting an interface by the very nature of how interfaces can be reused across more scenarios. e.g. Not that you would be injecting one but INotifyPropertyChanged pre-dated WPF but not plays a huge role in WPF and MVVM.
Restrictive:
public EditPatientViewModel (SqlPersistenceService svc) {}
Not so restrictive
public EditPatientViewModel (IPersistenceService svc) {}
Deciding between restriction and freedom (Interfaces and Dependency Injection)
That's completely up to you but if you inject interfaces then you will obtain:
decoupling between contract and implementation and all the baggage that goes with it
improved abstraction - hide away unnecessary details
I was reading "The Art of Unit Testing" by Roy Osherove and I think he answers my question.
He's talking about DI in testing and mentions, some people believe this hurts object oriented design principles (namely breaking encapsulation).
Object oriented principles are are there to enforce constraints on the end user of the API so that the object model is used properly and is protected from unintentional usage. Tests for example add another end user. Encapsulating these external dependencies somewhere without allowing anyone to change them, having private constructors or sealed classes, having non-virtual methods are all classic signs of overprotective design.
I think my problem was the fact that I feel like too many dependencies being injected were breaking encapsulation principles but adding these dependencies cater to the end user in a way where they actually need the functionality (like tests) and don't break any encapsulation rules.

Dependency injection through constructor or attribute? [duplicate]

I'm refactoring a class and adding a new dependency to it. The class is currently taking its existing dependencies in the constructor. So for consistency, I add the parameter to the constructor.
Of course, there are a few subclasses plus even more for unit tests, so now I am playing the game of going around altering all the constructors to match, and it's taking ages.
It makes me think that using properties with setters is a better way of getting dependencies. I don't think injected dependencies should be part of the interface to constructing an instance of a class. You add a dependency and now all your users (subclasses and anyone instantiating you directly) suddenly know about it. That feels like a break of encapsulation.
This doesn't seem to be the pattern with the existing code here, so I am looking to find out what the general consensus is, pros and cons of constructors versus properties. Is using property setters better?
Well, it depends :-).
If the class cannot do its job without the dependency, then add it to the constructor. The class needs the new dependency, so you want your change to break things. Also, creating a class that is not fully initialized ("two-step construction") is an anti-pattern (IMHO).
If the class can work without the dependency, a setter is fine.
The users of a class are supposed to know about the dependencies of a given class. If I had a class that, for example, connected to a database, and didn't provide a means to inject a persistence layer dependency, a user would never know that a connection to the database would have to be available. However, if I alter the constructor I let the users know that there is a dependency on the persistence layer.
Also, to prevent yourself from having to alter every use of the old constructor, simply apply constructor chaining as a temporary bridge between the old and new constructor.
public class ClassExample
{
public ClassExample(IDependencyOne dependencyOne, IDependencyTwo dependencyTwo)
: this (dependnecyOne, dependencyTwo, new DependnecyThreeConcreteImpl())
{ }
public ClassExample(IDependencyOne dependencyOne, IDependencyTwo dependencyTwo, IDependencyThree dependencyThree)
{
// Set the properties here.
}
}
One of the points of dependency injection is to reveal what dependencies the class has. If the class has too many dependencies, then it may be time for some refactoring to take place: Does every method of the class use all the dependencies? If not, then that's a good starting point to see where the class could be split up.
Of course, putting on the constructor means that you can validate all at once. If you assign things into read-only fields then you have some guarantees about your object's dependencies right from construction time.
It is a real pain adding new dependencies, but at least this way the compiler keeps complaining until it's correct. Which is a good thing, I think.
If you have large number of optional dependencies (which is already a smell) then probably setter injection is the way to go. Constructor injection better reveals your dependencies though.
The general preferred approach is to use constructor injection as much as possible.
Constructor injection exactly states what are the required dependencies for the object to function properly - nothing is more annoying than newing up an object and having it crashing when calling a method on it because some dependency is not set. The object returned by a constructor should be in a working state.
Try to have only one constructor, it keeps the design simple and avoids ambiguity (if not for humans, for the DI container).
You can use property injection when you have what Mark Seemann calls a local default in his book "Dependency Injection in .NET": the dependency is optional because you can provide a fine working implementation but want to allow the caller to specify a different one if needed.
(Former answer below)
I think that constructor injection are better if the injection is mandatory. If this adds too many constructors, consider using factories instead of constructors.
The setter injection is nice if the injection is optional, or if you want to change it halfway trough. I generally don't like setters, but it's a matter of taste.
It's largely a matter of personal taste.
Personally I tend to prefer the setter injection, because I believe it gives you more flexibility in the way that you can substitute implementations at runtime.
Furthermore, constructors with a lot of arguments are not clean in my opinion, and the arguments provided in a constructor should be limited to non-optional arguments.
As long as the classes interface (API) is clear in what it needs to perform its task,
you're good.
I prefer constructor injection because it helps "enforce" a class's dependency requirements. If it's in the c'tor, a consumer has to set the objects to get the app to compile. If you use setter injection they may not know they have a problem until run time - and depending on the object, it might be late in run time.
I still use setter injection from time to time when the injected object maybe needs a bunch of work itself, like initialization.
I personally prefer the Extract and Override "pattern" over injecting dependencies in the constructor, largely for the reason outlined in your question. You can set the properties as virtual and then override the implementation in a derived testable class.
I perfer constructor injection, because this seems most logical. Its like saying my class requires these dependencies to do its job. If its an optional dependency then properties seem reasonable.
I also use property injection for setting things that the container does not have a references to such as an ASP.NET View on a presenter created using the container.
I dont think it breaks encapsulation. The inner workings should remain internal and the dependencies deal with a different concern.
One option that might be worth considering is composing complex multiple-dependencies out of simple single dependencies. That is, define extra classes for compound dependencies. This makes things a little easier WRT constructor injection - fewer parameters per call - while still maintaining the must-supply-all-dependencies-to-instantiate thing.
Of course it makes most sense if there's some kind of logical grouping of dependencies, so the compound is more than an arbitrary aggregate, and it makes most sense if there are multiple dependents for a single compound dependency - but the parameter block "pattern" has been around for a long time, and most of those that I've seen have been pretty arbitrary.
Personally, though, I'm more a fan of using methods/property-setters to specify dependencies, options etc. The call names help describe what is going on. It's a good idea to provide example this-is-how-to-set-it-up snippets, though, and make sure the dependent class does enough error checks. You might want to use a finite state model for the setup.
I recently ran into a situation where I had multiple dependencies in a class, but only one of the dependencies was necessarily going to change in each implementation. Since the data access and error logging dependencies would likely only be changed for testing purposes, I added optional parameters for those dependencies and provided default implementations of those dependencies in my constructor code. In this way, the class maintains its default behavior unless overridden by the consumer of the class.
Using optional parameters can only be accomplished in frameworks that support them, such as .NET 4 (for both C# and VB.NET, though VB.NET has always had them). Of course, you can accomplish similar functionality by simply using a property that can be reassigned by the consumer of your class, but you don't get the advantage of immutability provided by having a private interface object assigned to a parameter of the constructor.
All of this being said, if you are introducing a new dependency that must be provided by every consumer, you're going to have to refactor your constructor and all code that consumers your class. My suggestions above really only apply if you have the luxury of being able to provide a default implementation for all of your current code but still provide the ability to override the default implementation if necessary.
Constructor injection does explicitly reveal the dependencies, making code more readable and less prone to unhandled run-time errors if arguments are checked in the constructor, but it really does come down to personal opinion, and the more you use DI the more you'll tend to sway back and forth one way or the other depending on the project. I personally have issues with code smells like constructors with a long list of arguments, and I feel that the consumer of an object should know the dependencies in order to use the object anyway, so this makes a case for using property injection. I don't like the implicit nature of property injection, but I find it more elegant, resulting in cleaner-looking code. But on the other hand, constructor injection does offer a higher degree of encapsulation, and in my experience I try to avoid default constructors, as they can have an ill effect on the integrity of the encapsulated data if one is not careful.
Choose injection by constructor or by property wisely based on your specific scenario. And don't feel that you have to use DI just because it seems necessary and it will prevent bad design and code smells. Sometimes it's not worth the effort to use a pattern if the effort and complexity outweighs the benefit. Keep it simple.
This is an old post, but if it is needed in future maybe this is of any use:
https://github.com/omegamit6zeichen/prinject
I had a similar idea and came up with this framework. It is probably far from complete, but it is an idea of a framework focusing on property injection
It depends on how you want to implement.
I prefer constructor injection wherever I feel the values that go in to the implementation doesnt change often. Eg: If the compnay stragtegy is go with oracle server, I will configure my datsource values for a bean achiveing connections via constructor injection.
Else, if my app is a product and chances it can connect to any db of the customer , I would implement such db configuration and multi brand implementation through setter injection. I have just taken an example but there are better ways of implementing the scenarios I mentioned above.
When to use Constructor injection?
When we want to make sure that the Object is created with all of its dependencies and to ensure that required dependencies are not null.
When to use Setter injection?
When we are working with optional dependencies that can be assigned reasonable default values within the class. Otherwise, not-null checks must be performed everywhere the code uses the dependency.
Additionally, setter methods make objects of that class open to reconfiguration or re-injection at a later time.
Sources:
Spring documentation ,
Java Revisited

How should common references be passed around in an assembly?

I am trying to get rid off static classes, static helper methods and singleton classes in my code base. Currently, they are pretty much spread over the whole code, especially so for the utility classes and the logging library. This is mainly due to the need for mocking ability as well as object-oriented design and development concerns, e.g. extensibility. I might also need to introduce some form of dependency injection in the future and would like to leave an open door for that.
Basically, the problem I have encountered is about the method of passing the commonly used references around. These are objects that are used by almost every class in the code base, such as the logging interface, the utility (helper) class interface and maybe an instance of a class that holds an internal common state for the assembly which most classes relate to.
There are two options, as far as I'm aware. One is to define a class (or an interface) that stores the common references, a context if you will, and pass the context to each object that is created. The other option is to pass each common reference to almost every class as a separate parameter which would increase the number of parameters of the class constructors.
Which one of these methods is better, what are the pros and cons of each, and is there a better method for this task?
I generally go with the context object approach, and pass the context object either to an object's constructor, or to a method -- depending on which one makes the most sense.
The context object pattern can take a few forms.
You can define an interface that has exactly the members you need, or you can generate a sort of container class. For example, when writing loosely-coupled components, I tend to have each component I implement have a matching interface, so that it can be reimplemented if desired. Then I register the objects on a "manager" object, something like this:
public interface IServiceManager
{
public T GetService<T>();
public T RequireService<T>();
public void RegisterService<T>(T service);
public void UnregisterService<T>(T service);
}
Behind the scenes there is a map from type to object, which allows me to extremely quickly assemble a large set of diverse components into a working whole. Each component asks for the others by interface, and the manager object is what glues them together. (If you correctly author your components, you can even swap out one service for another while the process is running!)
One would register a service something along these lines:
class FooService : IFooService { }
// During process start-up:
serviceManager.RegisterService<IFooService>(new FooService());
There is more overhead with this approach than with the flat-interface approach due to the dictionary lookup, but it has allowed me to build very sophisticated systems that can be easily redeployed with different service implementations. (And, as is usual, any bottlenecks I encounter are never in looking up a service object from a dictionary, but somewhere else such as the database.)
You're going to get varied opinions, but generally passing a separate parameter to the constructor for each dependency is preferred for a few reasons:
It clearly defines the actual dependencies for a class - with a "context" you don't know which parts of the context are used without digging into the code.
Generally having a lot of parameters to a constructor is a design smell, so using constructor injection helps you sniff out design flaws.
When testing you can mock out individual dependencies versus having to mock an entire context
I would suggest passing as a parameter to the constructor. This has great advantage for both dependency injection and unit testability ( mocking).

Passing constructor parameters when resolving types in Unity: Best practice

It's sometimes necessary when using dependency injection to provide the parameters to use in the constructor. This is something that's supported in Unity (and other dependency injection containers), so that when it tries to create an instance of the type, it can provide your arguments as parameters in the constructor.
My question is: is this approach desirable?
Within an interface it is not possible to specify which parameters an implementing class must have. By specifying the parameters to Unity, you are assuming that the implementing class has these parameters, and you are placing implicit constraints over future implementing classes. These constraints cannot be communicated through the interface.
So, is this is flaw in how interfaces themselves are specified (in .NET), eg. should it be possible to specify constructor signatures? Or has this feature (of being able to provide constructor parameters) been included in Unity due to some other need?
The only real workable approach (to me) seems to be use a factory to create the implementing classes, and do dependency injection on the factory.
I appreciate my question here might not be clear, so I'll ask it slightly differently: what's the best way to do dependency injection on a class which has a constructor requiring parameters?
(I do not believe this question to be subjective, as there should probably be a single design pattern for this type of dependency injection.)
EDIT:
I should add, that my main problem is that I may create a new implementing class which has additional constructor parameters (where the constructor parameters are not things that can be created by unity).
I'm not sure where you got the idea that constructor injection does not fit with DI. I'd say that the real situation is the opposite of that: constructor injection is one of the most common patterns utilised to achieve dependency injection - I'd go as far as saying that it is the most common pattern, and that view is certainly backed up by the fact that that majority of Inversion of Control containers (DI containers) use constructor injection as their preferred mechanism.
StructureMap for example has a core, very specific support for constructor injection where it will pick the constructor with the most parameters as the constructor used for dependency resolution.
What you are saying by using the constructor injection pattern is that "I am removing the hard coded dependencies within my class by specifying them as parameters passed into the constructor - my class cannot be instantiated without these dependencies". Of course, the first half of that statement is the essence of DI, but the second half enforces this more.
Dependencies are an implementation detail that should be able to be changed easily, providing a flexible, loosely coupled solution. They are about the how, not the what. Interfaces specify the what. So I'd say that your suggestion of specifying dependencies in interfaces actually goes against the concept of dependency injection.
And as far as your statement about factories - this is exactly what IOC containers are - great big factories that take care of a solution's dependency tree, so you don't need to care.
Edit
I think maybe you are asking about the case where you want to provide a non-dependency constructor parameter, such as an id for a referenced entity, or an initial state enum?
I personally don't see a problem with an IOC container allowing for this. It is still initial state of your class and hence the rules for the creation of that state need to be explicitly expressed. It can mean that you sometimes need more references to your IOC container that you might like, but it is not a horrible enough situation to abandon the other benefits of counstructor injection.
The responsibility of IoC containers (say Unity) is to connect interfaces with concrete implementations. That means your container must know the interface and how to create the object that implements the interface. Using constructor injection is perfectly legal and the recommended way. Unity will create the concrete implementation when your application requests an interface through the Resolve() method.
The Unity container itself is the factory that creates your objects, you use Unity because you don't want to implement those factories by yourself.
The issue here is the definition of the InjectionConstructor in Unity vs say the one in Castle.Windsor.
In Unity, if you need to inject a particular parameter, say an AppSetting you are also forced to supply all the other parameters thus fixing the signature of the constructor. However, in Castle.Windsor it takes the parameter you've supplied and then uses the resolution mechanism to locate the other paramaters in the normal way.
It would be possible to introduce this into Unity by writing a custom Builder strategy that did a "best-fit" approach to which constructor to use rather than the default greedy/supply everything which is the default.

Pattern for objects initialization at startup

I'm building an application and as time goes on, I have more and more objects to initialize at startup. Moveover, some of the newer objects depend on others so I'm getting some kind of spaggetti initialization where objects are created then passed to other constructors. I'm suspecting that I'm getting it wrong.
For example I have a WinForm which accepts a "Controller" class and 2 events. The controller needs to be told about the existence of a DataGridView from the WinForm so it has a method
Controller::SetDataGridReference(DataGridView^ dgv)
Is there a general method of instanciating objects at startup then referencing those objects to each another?
I've been told that putting all the required classes as constructor parameters is a good practice but frankly, I don't see how I can do that here.
I don't really think that the language matters
This looks like a textbook case for using dependency injection (DI). It will certainly help with your spaghetti code and can even assist with unit testing. If you want to make a gradual migration towards DI you might want to consider refactoring the objects with similar relationships and using a few sets of factory classes that can handle all the boilerplate chain intialization as well as centralizing where all that takes place in your code base.
I can recommend Google Guice as a good DI framework for Java. Even if you arent using Java it is a good DI model to compare against other language's DI frameworks
Two patterns pop into mind as possibly appropriate depending on the specifics of your problem:
Abstract Factory Pattern. This can work with or without the Dependency Injection approach suggested by #Scanningcrew.
Mediator Pattern. Construct a mediator. Pass the mediator into the constructor of each object. Have each object register with the mediator. Then the objects don't need to know about each other explicitly. This works well when you have a set number of objects interacting with each other.
Use the Controller Design Pattern.
That is, create a SINGLE class that will be instanced on program initialization, called Controller. On the constructor of that class, create all other objects. Whatever object that needs any other objects should receive said object as a parameter on its constructor. No one, no absolutely any other object should create anything on their constructor. Pass everything as parameters on their constructors. Also, on the Controller class destructor/dispose call all objects destructor/dispose method in reverse order. This won't reduce your code, but it will make if far better to understand and debug later on.
Dependency Injection should help here: at application boot you can choice to build the complete (or sort of) graph of objects. The entry point of your application will instantiate the DI container of your choice, the you just request the root object.
For example Google Guice comes with a very nice Object grapher.
For the objects interaction, I would go for a Mediator. Check out this definition:
"Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently."
For the instantiation, I would consider the Dependency Injection. Remember that you can freely use and mix design patterns to achieve your goals.

Categories

Resources