I've seen frameworks like Ninject as well as posts on Stack speak about self binding when using dependency injection frameworks like in the code below.
Bind<Samurai>().To<Samurai>();
They even go to the extent of having special syntax for this:
Bind<Samurai>().ToSelf();
Why would you want to bind a type to itself? I don't see any practical applications for where this might be useful and help reduce dependencies in code. Wouldn't this just mean a reference to a type would simply resolve to itself?
When applying Dependency Injection and adhering to the Dependency Inversion Principle, the common advice is to program to interfaces, not implementations. That's why most of the time you'll see bindings that go from an abstraction to an implementation:
Bind<IWarrior>().To<Samurai>();
This means that components depend on IWarrior at compile time, while you inject a Samurai at runtime.
Under certain conditions, however, it makes sense to have mapping from a concrete component to itself. In other words, in case 'someone' requires a Samurai, you supply it with that Samurai.
The most prominent case is when resolving root types. Root types are the top of the dependency graph; root types are resolved directly from the container. All other components are direct or indirect dependencies of a root type.
Often you'll see that those root types are resolved by their concrete types and this happens, for instance, when dealing with UI frameworks. Examples of such are Web Forms Pages, MVC Controllers, Web API ApiControllers, etc.
Some DI containers allow concrete unregistered types to be resolved anyway (although in recent years several DI Containers for .NET have disabled the ability to resolve concrete unregistered types by default). This might lead you to believe that a self-binding is redundant, but that is not always the case. Adding such binding explicitly lets the container know about the existence of such binding. This has the advantage of using the container's diagnostic abilities (if present) to scan the object graphs for errors. In case of the absence of such feature, one can usually iterate the known registrations and do some verification inside a unit test. For such verification to be meaningful when the container's registrations are iterated over, all root types need to be registered in the container. Otherwise this verification process will result in false-negatives.
Another reason why you want to tell the DI container about a self-binding is when you need the type to be registered with a different lifestyle than the container's default lifestyle. Most containers will give you a Transient instance, in case the type isn't registered.
Related
Reading the Simple injector docs to get a handle on how it all works and I read the below paragraph. I understand what its explaining apart from the part in bold. What does it mean?
The technique for keeping this dependency to a minimum can be achieved by designing the types in your application around the constructor injection pattern: Define all dependencies of a class in the single public constructor of that type; do this for all service types that need to be resolved and resolve only the top most types in the application directly (i.e. let the container build up the complete graph of dependent objects for you)
Ignoring my lack of understanding regarding the sentence above I ploughed on but when trying to set up Simple injector for Web api came across this line of code container.RegisterWebApiControllers(GlobalConfiguration.Configuration); With this explanation
Because controllers are concrete classes, the container will be able to create them without any registration.
Does this mean if I have a bunch of classes that don't rely on an interface, I can create them using a single line of code? (if so how, should I).
What this means is a good practice of not relying on the DI-container in your code apart from some top-level where you have to do that to "kick-start" the application.
That will mean that all your classes will just have constructor dependencies in the form of interfaces and will not do Container.Resolve. This will only be called on the top level of you application.
In some frameworks you won't even have to do that yourself because it's a part of how framework operates. As far as I remember in .Net core e.g. you won't need to do a resolve, but it will happen inside framework when the controllers will be initiated.
Because controllers are concrete classes, the container will be able
to create them without any registration.
This means you won't have to register the controllers themselves in the container. Container will only resolve controller dependencies themselves, create controllers and pass all of the resolved dependencies in them.
P.S. Resolving only in the root of you application is nothing specific for the SimpleInjector. It is a good practice that can be applied to any container and SimpleInjector can be used even if you don't follow it, which probably no one these days would recommend.
do this for all service types that need to be resolved and resolve only the top most types in the application directly
What this means is that, once you solely use Constructor Injection as a way for a class to get a hold of its dependencies, you will end up building object graphs that are potentially many layers deep. Take this object graph for instance:
new HomeController(
new ProductService(
new SqlProductRepository(
new CommerceContext(connectionString)),
new AspNetUserContextAdapter(
httpContextAccessor)));
PRO TIP: Did you know that you can let Simple Injector visualize your object graphs for you inside the debugger? This is explained here.
Here you see that HomeController has one dependency (IProductService) that it gets through its constructor. ProductService itself has two dependencies (IProductRepository and IUserContext) that are as well supplied through its constructor. This can go many layers deep.
Having Constructor Injection as the sole means to supply dependencies to a class means that the class is not allows to request them itself by calling back into the Container. This is a well-established anti-pattern called Service Locator. Constructor Injection simplifies your classes and allows the Container to analyze the object graph for you and detect any anomalies.
and resolve only the top most types in the application directly
When the whole object graph is constructed using Constructor Injection, it means that you only have to ask for a HomeController, which is the top most type in the graph. Nothing depends on HomeController; HomeController depends on everything (implicitly). All application behavior is invoked through these top most types. In an MVC application these typically are controllers, HTTP handlers and modules.
Because controllers are concrete classes, the container will be able to create them without any registration.
This statement is a bit misleading. Yes, it is true that Simple Injector will be able to create a requested concrete type for you, even if that type isn't registered. As explained here in the documentation however, it is best to always register your root types in the container. This ensures that the container knows about those types and it allows analysis and verification on those types as well. Not registering those concrete root types will give you a false sense of security when you call container.Verify(). Verify is only able to verify on the registrations that it knows of. When an unregistered concrete type is referenced as a dependency, the container still knows about it, but that obviously doesn't hold for root types, since nothing depends on them.
WARNING: In Simple Injector v5, this behavior is likely going to change. By default, Simple Injector v5 will probably not allow concrete unregistered root types to be resolved. see
I need to be able to work with DI Container as a "context". That means, in different contexts the same interface should be resolved with different implementations.
Practically, on resolve one container should look for implementations in one set of assamblies, the other container in an other set.
As this should not be totally dynamic, it could be easily configured per container in the configuration file, which can be loaded by name. There would be multiple implementations of the same interface registered with name in the container, so I could do ResolveAll().
Unfortunatelly, the schema of the unity configuration tells me that the element is bound to the whole Unity "runtime" and not to one or the other container.
Is there any other way to achieve this with Unity? Or can anyone suggest an other IoC framework that can do this?
PS1: I know that it sounds a little bit like plugin architecture, but it is not, and I need the power of DI.
PS2: I could try to reference all assamblies on unity level, and narrow the search on container level using just namespaces and type names, but I can not guarantee that those names will remain unique. The only certain thing is the assambly.
Thank you
This question already has answers here:
Is there a pattern for initializing objects created via a DI container
(5 answers)
Closed 7 years ago.
I'm working on a project in which my constructors contain - only - behavioral dependencies. i.e. I never pass values / state.
Example:
class ProductProcessor : IProductProcessor
{
public double SomeMethod(){ ... }
}
class PackageProcessor
{
private readonly IProductProcessor _productProcessor;
private double _taxRate;
public PackageProcessor(IProductProcessor productProcessor)
{
_productProcessor = productProcessor;
}
public Initialize(double taxRate)
{
_taxRate = taxRate;
return this;
}
public double ProcessPackage()
{
return _taxRate * _productProcessor.SomeMethod();
}
}
In order to pass state, it was decided to include a second step (a call to Initialize).
I know we can configure this as a named parameter in the IoC Container config class, however, we did not like the idea of creating "new namedParameter(paramvalue)'s" in the configuration file as it makes it unnecessarily unreadable and creates a future maintenance pain spot.
I've seen this pattern in more than one place.
Question: I read some consider this two step initialization an anti-pattern. If that is the consensus, wouldn't this imply a limitation / weakness of sorts in the approach of dependency injection via a IoC container?
Edit:
After looking into Mark Seeman's suggestion:
and the answers to this one, I have a few comments:
Initialize/Apply : Agree on it being an anti pattern / smell.
Yacoub Massad: I agree IoC containers are a problem when it comes to primitive dependencies. Manual (poor man's) DI, as described here sounds great for smaller or architecturally stable systems but I think it could become very hard to maintain a number of manually configured composition roots.
Options:
1)Factories as dependencies (when run time resolution is required)
2) Separate stateful object from pure services as described here.
(1): This is what I had been doing but I realized that there is a potential to incur into a another anti-pattern: the service locator.
(2): My preference for my particular case is this one about this one as I can cleanly separate both types. Pure services are a no brainer - IoC Container, whereas stateful object resolution will depend on whether they have primitive dependencies or not.
Every time I've 'had' to use dependency injection, it has been used in a dogmatic way, generally under the orders of a supervisor bent on applying DI with IoC container at any cost.
I read some consider this two step initialization an anti-pattern
The Initialize method leads to Temporal Coupling. Calling it an anti-pattern might be too strict, but it sure is a Design Smell.
How to provide this value to the component depends on what type of value it is. There are two flavors: configuration values and runtime values:
Configuration Values: If it is a constant/configuration value that won't change during the lifetime of the component, the value should be injected into the constructor directly.
Runtime values: In case the value changes during runtime (such as request specific values), the value should not be provided during initialization (neither through the constructor nor using some Initialize method). Initializing components with runtime data actually IS an anti-pattern.
I partly agree with #YacoubMassad about the configuration of primitive dependencies using DI containers. The APIs provided by containers do not enable setting those values in a maintainable way when using auto-wiring. I think this is mainly caused by limitations in C# and .NET. I struggled a long time with such API while designing and developing Simple Injector, but decided to leave out such API completely, because I didn't find a way to define an API that was both intuitive and lead to code that was easy maintainable for the user. Because of this I usually advise developers to extract the primive types into Parameter Objects and instead register and inject the Parameter Object into the consuming type. In other words, a TaxRate property can be wrapped in a ProductServiceSettings class and this Parameter Object can be injected into ProductProcessor.
But as I said, I only partly agree with Yacoub. Although it is more practical to compose some of your objects by hand (a.k.a. Pure DI), he implies that this means you should abandon DI containers completely. IMO that is too strongly put. In most of the applications I write, I batch-register about 98% of my types using the container, and I hand-wire the other two 2%, because auto-wiring them is too complex. This gives in the context of my applications the best overall result. Of course, you're mileage may vary. Not every application really benefits from using a DI container, and I don't use a container myself in all the application I write. But what I always do however, is apply the Dependency Injection pattern and the SOLID principles.
The taxRate in your example is a Primitive Dependency. And primitive dependencies should be injected normally in the constructor like the other dependencies. Here is how the constructor would look like:
public PackageProcessor(IProductProcessor productProcessor, double taxRate)
{
_productProcessor = productProcessor;
_taxRate = taxRate;
}
The fact that DI containers do not nicely/easily support primitive dependency is a problem/weakness of DI containers in my opinion.
In my opinion, it is better to use Pure DI for object composition instead of a DI container. One reason is that it supports easier injection of primitive dependencies. See this article also for another reason.
Using the Initialize method has some problems. It makes the construction of an object more complex by requiring the invocation of the Initialize method. Also, a programmer might forget to call the Initialize method, which leaves your object in an invalid state. This also means that the taxRate in this example is a hidden dependency. Programmers wouldn't know that your class depends on such primitive dependency by simply looking into the constructor.
Another problem with the Initialize method is that it might be called twice with different values. Constructors on the other hand, ensure that dependencies do not change. You would need to create a special boolean variable (e.g. isInitialized) to detect if the Initialize method has been called already. This just complicates things.
I'm building a MVC application with Autofac and EntityFramework. I have a large set of data repositories / business objects that use my logging interface (NLog). I have just started working with Autofac and would like to know the preferred way for property injection:
Pass ILogging as constructor property, for this I have to set each local property from the constructor and creates larger constructor footprints.
Register each object individually with Autofac (they do not share a generic interface)
Use an Autofac.Module to locate these objects and set the property with reflection
Create a generic interface ILoggerDependency and register this with Autofac, this way all objects are easely registred.
My preferred method (out of lazyness...) is to have a generic interface that I can register with Autofac.
I am not that familiar with Autofac, so I'll try to give you my best recommendation based on what I know.
If there is one thing a lot of people gets wrong with dependency injection, it has to be using it for automation. The goal of DI is not to remove magic from your code. If anything, it is quite the opposite.
Keeping that in mind, I would not even consider using reflection as it hides large amounts of fragile plumbing.
Next, interfaces in OOP are meant to express what an object can do. Being injected is definitely not an action an object can take, but rather something that is imposed on an object. Even though, it is a quick and dirty way to solve your issue, I would refrain from using it as it will denature the structure of your code.
I have trouble understanding what you mean by pass ILogging as constructor property. Basically, you mean to resolve the interface yourself in the constructor? This looks a lot like property injection which defeats the purpose of DI by adding a strong dependency on your container within your class. Basically, instead of depending on Log4Net, you end up depending on Autofac. To fix this, you would need to add a service locator and then you still end up with a similar problem. How do you inject your service locator?
This is why I would register each object individually. It lets your container do its job. It doesn't affect your code structure and abstractions. It doesn't uses reflection (magic). It doesn't force you to depend on your container within each class. Besides, it also gives you a centralized place to look for when adding or removing repositories from your code.
I'm trying to understand what CompositionRoot is about.
Right up to now I never found a deep description of what it is about,
only short statements of what shall not be done.
Is the Bootstrapper that comes along when leveraging caliburn.micro already that what is meant "CompositionRoot"?
Or is it closer to the servicelocator antipattern, as it can deliver merely anything that is inside the assembly and it's dependencies.
If someone has a good description of CompositionRoot, please share.
I already know the ploeh blog.
If I see that CompositionRoot leads to better architecture and / or helps me solve problems, I'm still willing to buy the book. But right know there is not enough
information around for me to see what it will help.
update
Let's pretend that all of my ViewModels get an EventAggregator injected (constructor injection). Now I want to dynamically create those ViewModels when they are needed.
I can register types beforehand (in the CompositionRoot), but how would I resolve dependencies later? As far as I understand, the Container should not be touched after the composition root. Definitly I do not want to create all instances before I need them (that would make the application start slow). Is "Register - Resolve - Release" meant here?
(that pattern is coined in the ploeh blog, too)
I assume you've seen Mark's article at http://blog.ploeh.dk/2011/07/28/CompositionRoot.
As it states:
A Composition Root is a (preferably) unique location in an application where modules are composed together.
And that this should be:
As close as possible to the application's entry point.
In the case of Caliburn.Micro, the Bootstrapper class provides a ConfigureContainer method for you to override and compose you modules.
Ideally, it will only be your composition root that has a reference to your IoC container.
Caliburn.Micro will resolve your shell view model (if you use the generic version of the Bootstrapper) via your container.
It does also supply a static IoC class which is an implementation of the Service Locator (anti) pattern if you do need to reference the container outside of your composition root.
Update
If you wish to resolve types via your container at runtime after your composition root (for example if you have complex dependency chains) then use factory types.
These factory types would also have a reference to your IoC container. You could either:
Pass a reference to your container as a dependency to the factory type
Use the Service Locator pattern in your factories (e.g. the Caliburn.Micro IoC class)
Some IoC containers such as Castle Windsor and (using an extension) Ninject will generate factory types for you based on a factory interface and conventions (this is the nicest option)