In Ninject, how can I run custom code on an object after it is created with Bind<..>.ToSelf()? - dependency-injection

In Ninject's dependency injection, if you set up a binding of a class to itself like so:
Bind<SomeClass>().ToSelf();
Ninject very nicely resolves any dependencies SomeClass has and gives you the object back. I want to be able to do something to the SomeClass it returns every time it creates a new one, so like a post-processing event. I could use the .ToMethod (or ToFactoryMethod) binding to explicitly new it up, but I would like all its dependencies resolved by Ninject beforehand.
It wouldu be nice to do something like:
Bind<SomeClass>()
.ToSelf()
.After(sc => sc.MethodIWantToCall()); // then after here, Ninject returns the object.
Is there some way to do this in Ninject 1.0/1.1?

If you can't put the code you want to execute in the constructor, you can implement IInitializable or IStartable. The former provides an Initialize() method that gets called after all injection has completed, and the latter provides both a Start() and Stop() method, called during activation and deactivation, respectively.

I ran into the same problem, but I could not use Nate's solution because I couldn't make the type implement IInitializable. If you're in a similar boat, you can use .OnActivation and avoid having to modify the definition of the target types:
Bind<SomeClass>().ToSelf().OnActivation(x => ((SomeClass)x).MyInitialize());
You can see how we call some arbitrary initialization method (MyInitialize) upon activation (instantiation) of the class.
This has the advantage of not baking in a hard dependency to Ninject in your own classes (aside from your modules, of course), thus allowing your types to remain agnostic about the DI-framework you end up using.

Related

Dependency Injection and/vs Global Singleton

I am new to dependency injection pattern. I love the idea, but struggle to apply it to my case. I have a singleton object, let’s call it X, which I need often in many parts of my program, in many different classes, sometimes deep in the call stack. Usually I would implement this as a globally available singleton. How is this implemented within the DI pattern, specifically with .NET Core DI container? I understand I need to register X with the DI container as a singleton, but how then I get access to it? DI will instantiate classes with constructors which will take reference to X, that’s great – but I need X deep within the call hierarchy, within my own objects which .NET Core or DI container know nothing about, in objects that were created using new rather than instantiated by the DI container.
I guess my question is – how does global singleton pattern aligns/implemented by/replaced by/avoided with the DI pattern?
Well, "new is glue" (Link). That means if you have new'ed an instance, it is glued to your implementation. You cannot easily exchange it with a different implementation, for example a mock for testing. Like gluing together Lego bricks.
I you want to use proper dependency injection (using a container/framework or not) you need to structure your program in a way that you don't glue your components together, but instead inject them.
Every class is basically at hierarchy level 1 then. You need an instance of your logger? You inject it. You need an instance of a class that needs a logger? You inject it. You want to test your logging mechanism? Easy, you just inject something that conforms to your logger interface that logs into a list and the at the end of your test you can check your list and see if all the required logs are there. That is something you can automate (in contrast to using your normal logging mechanism and checking the logfiles by hand).
That means in the end, you don't really have a hierarchy, because every class you have just gets their dependencies injected and it will be the container/framework or your controlling code that determines what that means for the order of instantiation of objects.
As far as design patterns go, allow me an observation: even now, you don't need a singleton. Right now in your program, it would work if you had a plain global variable. But I guess you read that global variables are "bad". And design patterns are "good". And since you need a global variable and singleton delivers a global variable, why use the "bad", when you can use the "good" right? Well, the problem is, even with a singleton, the global variable is bad. It's a drawback of the pattern, a toad you have to swallow for the singleton logic to work. In your case, you don't need the singleton logic, but you like the taste of toads. So you created a singleton. Don't do that with design patterns. Read them very carefully and make sure you use them for the intended purpose, not because you like their side-effects or because it feels good to use a design pattern.
Just an idea and maybe I need your thought:
public static class DependencyResolver
{
public static Func<IServiceProvider> GetServiceProvider;
}
Then in Startup:
public void Configure(IApplicationBuilder app, IServiceProvider serviceProvider)
{
DependencyResolver.GetServiceProvider = () => { return serviceProvider; };
}
And now in any deed class:
DependencyResolver.GetServiceProvider().GetService<IService>();
Here's a simplified example of how this would work without a singleton.
This example assumes that your project is built in the following way:
the entry point is main
main creates an instance of class GuiCreator, then calls the method createAndRunGUI()
everything else is handled by that method
So your simplified code looks like this:
// main
// ... (boilerplate)
container = new Container();
gui = new GuiCreator(container.getDatabase(), container.getLogger(), container.getOtherDependency());
gui.createAndRunGUI();
// ... (boilerplate)
// GuiCreator
public class GuiCreator {
private IDatabase db;
private ILogger log;
private IOtherDependency other;
public GuiCreator(IDatabase newdb, ILogger newlog, IOtherDependency newother) {
db = newdb;
log = newlog;
other = newother;
}
public void createAndRunGUI() {
// do stuff
}
}
The Container class is where you actually define which implementations will be used, while the GuiCreator contructor takes interfaces as arguments. Now let's say the implementation of ILogger you choose has itself a dependency, defined by an interface its contructor takes as argument. The Container knows this and resolves it accordingly by instantiating the Logger as new LoggerImplementation(getLoggerDependency());. This goes on for the entire dependency chain.
So in essence:
All classes keep instances of interfaces they depend upon as members.
These members are set in the respective constructor.
The entire dependency chain is thus resolved when the first object is instantiated. Note that there might/should be some lazy loading involved here.
The only places where the container's methods are accessed to create instances are in main and inside the container itself:
Any class used in main receives its dependencies from main's container instance.
Any class not used in main, but rather used only as a dependency, is instantiated by the container and receives its dependencies from within there.
Any class used neither in main nor indirectly as a dependency somewhere below the classes used in main will obviously never be instantiated.
Thus, no class actually needs a reference to the container. In fact, no class needs to know there even is a container in your project. All they know is which interfaces they personally need.
The Container can either be provided by some third party library/framework or you can code it yourself. Typically, it will use some configuration file to determine which implementations are actually supposed to be used for the various interfaces. Third party containers will usually perform some sort of code analysis supported by annotations to "autowire" implementations, so if you go with a ready-made tool, make sure you read up on how that part works because it will generally make your life easier down the road.

Openrasta: Swap instance in dependency resolver

Suppose I register some instance in OpenRasta's dependency resolver using
resolver.AddDependencyInstance(IInterface, instance, DependencyLifetime.Singleton)
Now if I want to swap that instance later, say to reread fresh data from the db, is another call to resolver.AddDependencyInstance the right thing to do?
Checking the InternalDependencyResolver implementation, it seems to be fine. However I'm asking because the behavior is not defined (in openrasta's sources, where I checked), and the method prefix "Add" is suggestive of different behavior.
I wouldn't use Singleton if you have to swap the instance at some point.
Use DependencyLifetime.Transient and have a constructor injection in the class where you need the new instance

Avoiding dependency carrying

When coding, I often come across the following pattern:
-A method calls another method (Fine), but the method being called/callee takes parameters, so in the wrapping method, I pass in parameters. Problem is, this dependency carrying can go on and on. How could I avoid this (any sample code appreciated)?
Thanks
Passing a parameter along just because a lower-layer component needs it is a sign of a Leaky Abstraction. It can often be more effective to refactor dependencies to aggregate services and hide each dependency behind an interface.
Cross-cutting concerns (which are often the most common reason to pass along parameters) are best addressed by Decorators.
If you use a DI Container with interception capabilities, you can take advantage of those to implement Decorators very efficiently (some people refer to this as a container's AOP capabilities).
You can use a dependency injection framework. One such is Guice: see http://code.google.com/p/google-guice/
Step 1: Instead of passing everything as separate arguments, group the arguments into a class, let's say X.
Step 2: Add getters to the class X to get the relevant information. The callee should use the getters to get the information instead of relying on parameters.
Step 3: Create an interface class of which class X inherits. Put all the getters in the interface (in C++ this is as pure virtual methods).
Step 4: Make the called methods only depend on the interface.
Refactoring: Introduce Parameter Object
You have a group of parameters that naturally go together?
Replace them with an object.
http://www.refactoring.com/catalog/introduceParameterObject.html
The advantage of the parameter object is that the calls passing them around don't need to change if you add/remove parameters.
(given the context of your answers, I don't think that an IoC library or dependency injection patterns are really what you're after)
Since they cannot be (easily) unit tested, most developers choose to inject objects into Views. Since the views are not (normally) used to construct other views, that is where your DI chain ends. You may have the issue (which I have run into every once in ahwile) where you need to construct objects in the correct order especially when using a DI framework like Unity where an attemt to resolve the object will deadlock. The main thing you need to worry about is circular dependency. In order to do this, read the following article:
Can dependency injection prevent a circular dependency?

Can Autofac do automatic self-binding?

I know some DI frameworks support this (e.g. Ninject), but I specifically want to know if it's possible with Autofac.
I want to be able to ask an Autofac container for a concrete class, and get back an instance with all appropriate constructor dependencies injected, without ever registering that concrete class. I.e., if I never bind it explicitly, then automatically bind the concrete class to itself, as if I had called builder.Register<MyClass>();
A good example of when this would be useful is ViewModels. In MVVM, the layering is such that only the View depends on the ViewModel, and that via loose typing, and you don't unit-test the View anyway. So there's no need to mock the ViewModel for tests -- and therefore there's no reason to have an interface for each ViewModel. So in this case, the usual DI pattern of "register this interface to resolve to this class" is unnecessary complexity. Explicit self-binding, like builder.Register<MyClass>();, also feels like an unnecessary step when dealing with something as straightforward as a concrete class.
I'm aware of the reflection-based registration example in the Autofac docs, but that's not to my taste either. I don't want the complexity (and slowness) of registering every possible class ahead of time; I want the framework to give me what I need when I need it. Convention over configuration, and all that.
Is there any way to configure Autofac so it can say "Oh, this is a concrete type, and nobody registered it yet, so I'll just act like it had been registered with default settings"?
builder.RegisterTypesMatching(type => type.IsClass)
If you look at the source you will see that RegisterTypesMatching (and RegisterTypesFromAssembly) is NOT DOING ANY REFLECTION. All Autofac is doing in this case is registering a rule that accepts a type or not. In my example above I accept any type that is a class.
In the case of RegisterTypesFromAssembly, Autofac registers a rule that says "if the type you're trying to resolve have Assembly == the specified assembly, then I will give you an instance".
So:
no type reflection is done at register time
any type that matches the criteria will be resolved
Compared to register the concrete types directly, this will have a perf hit at resolve time since Autofac will have to figure out e.g. constructor requirements. That said, if you go with default instance scope, which is singleton, you take the hit only the first time you resolve that type. Next time it will use the already created singleton instance.
Update: in Autofac 2 there is a better way of making the container able to resolve anything. This involves the AnyConcreteTypeNotAlreadyRegistered registration source.
what about:
builder.RegisterTypesFromAssembly(Assembly.GetExecutingAssembly());
no reflection is done, as Peter Lillevold points out.

Dependency injection through constructors or property setters?

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

Resources