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)
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'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.
I recently finished reading Dino Esposito's great book Modern Web Development, and in it he addresses a suggestion for a Domain Driven Layered Architecture for web applications. I have always struggled with a specific piece of suggestions I have seen similar to the one below:
Specifically with reference to the IoC being made in the Infrastructure layer. I understand the reasoning behind this and it makes sense to me however how do you adequately implement that within the bounds of the ASP.NET MVC framework? To add a dependency resolver you need to implement the IDependencyResolver interface which exists in the System.Web.MVC namespace.
In past projects I would typically implement my IoC within the MVC application itself in the startup folder however this seems to be at odds with the suggestion for the layout.
I do not want to turn this into an opinion type of question, all I am looking for is a possible, actual concrete way to implement this pattern without dragging the System.Web.MVC namespace down to the infrastructure layer.
EDIT
To add a follow on diagram for the suggested architecture, and the part that is still confusing to me, it would appear that Dino's suggestion does indeed put the IoC container in the infrastructure assembly:
Answer to Your Question
Fundamentally, your question is "I am looking for is a possible, actual concrete way to implement this pattern without dragging the System.Web.MVC namespace down to the infrastructure layer"
There is a way to do this, and it involves introducing a new IoC container library, one dedicated for the purpose.
IDependencyResolver does not have to be your system wide resolution interface - it is just the interface used by MvC. There are other IoC containers, and a number of them provide adaptors to inject an implementation of IDependencyResolver that wraps their IoC logic.
This permits a few things:
The MvC components that depend on the ability to perform an explicit resolution can still depend on IDependencyResolver
Other layers in the system can depend on a different resolution interface, and thus contain a reference to an isolated fit-for-purpose assembly
Both the MvC layer and the other layers will all be accessing the same set of dependency/implementation registrations
Some examples of IoC containers that support this:
Autofac - with Autofac Mvc Support
You can see the last line of the sample is:
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
After that line, any MvC component that depends on IDependencyResolver will automatically get the AutofacDependencyResolver which wraps calls to the Autofac container
StructureMap - StructureMap.Mvc
Here is a comparison of a large number of c# IoC containers that may help you select the one that's right for you.
[Actual Implementation Concerns - aka My Opinion about Why this is NOT a good idea]
Your practice in your past projects of only using the IoC in the Mvc application is more correct, in my opinion, so the below concepts may already be familiar to you, but as you are considering referencing the IoC from the domain, I thought it worth exploring.
First question - Why?
While that answer provides a way to do what you're asking, based on that diagram, I confess it's not clear to me what the purpose is of depending on the IoC resolver from the domain layer, and why you would need to do that.
If you find yourself doing that, you may be accidentally using the Service Location Anti-Pattern
As outlined in that blog, there is no need to depend on the IoC resolver (or locator) - simply depend on the service you need, and let the IoC inject the appropriate implementation.
Part of the problem in understanding the intent is the diagram itself - it often happens that people draw diagrams by dropping on some boxes and connecting them up - without ever being clear about what the lines mean. Are they chains of dependency? Are they sequence of execution? What does it mean to have a line from the domain model box to the actual label of the infrastructure layer??? Is it depending on nothing? Or illustrative of a possible dependency that is not articulated here?
What should use the IoC resolver?
The only part of the system that should directly reference the IoC resolver is the composition root, which is effectively the entry point to the application. The first part 'wires up the object graph' - really, it registers how to resolve all possible dependencies from the interfaces that are depended on, to appropriate concrete implementations.
It then resolves the entry point object (or registers an IDependencyResolver so Mvc can resolve the entry point object, aka a controller). When the entry object is resolved, it automatically resolves all it's dependencies, in the process resolving next layer of dependencies, and so on all the way until you reach classes with no dependencies. Which is likely to be your domain layer, if you are doing DDD.
Dependency-less Domain Layer and the Onion Architecture
Since you are interested in DDD, the received wisdom is that the domain layer should not depend on anything that is not defined in the domain layer. If there is really a need to utilise the services of an infrastructure component such as a repository, use separated interfaces and put the interface in the domain layer, but the implementation in a concrete persistence layer.
The architectural pattern this lends itself to is known as the Onion Architecture also known as the Hexagonal Architecture
Using Other IoC Containers
While I don't think it's necessary to reference the IoC resolver/locator from the domain layer (or any layer, really), I do still think there is value in adopting a separate dedicated IoC container library, as outlined above.
The value is in some of the more flexible options for how to configure services, including some nifty convention based auto-configuration.
The one reason it might be worth depending on the IoC library in the domain layer is to co-locate the registration and configuration logic with the services that are being configured, which can help structure and organise your IoC dependency registrations. But just because you take a dependency on the IoC assembly to permit structuring your registrations, doesn't mean you should use the IoC resolver/locator.
I'm building a CMS and it has many extension points (Data/ContentTypes, Plugins, Macros, Themes) and some of those extensions need to register services. So far extensions only depend on 'MyProject.Core' library and it would be nice if they wouldn't be dependant on any specific IoC framework. Now I'm thinking if I should build another layer to hide IoC specific registrations. The problem is that I need some advanced functionality.
E.g. NHibernate implementation of 'Data/ContentType' services (Castle Windsor style)
container.Register(Component.For<IPageRepository>().ImplementedBy<NHPageRepository>());
container.Register(Component.For<ISessionFactory>().Instance(NHibernateHelper.CreateSessionFactory()));
container.Register(Component.For<ISession>().UsingFactoryMethod(c => c.Resolve<ISessionFactory>().OpenSession()).LifeStyle.PerWebRequest);
Third line is the "hard one". I could make an interface like
interface IMyContainer
{
Register<TService>(Func<IMyContainer,TService> factoryMethod)
Register<TService>(Func<IMyContainer,TService> factoryMethod, LifeStyle lifeStyle)
// ...
}
but "translating" this registration (my IoC abstraction)
public class NHInstaller : IInstaller
{
public void Install(IMyContainer container)
{
container.Register<ISession>(c => c.Resolve<ISessionFactory>().OpenSession(), LifeStyle.PerRequest);
}
}
to this (Windsor)
container.Register(Component.For<ISession>().UsingFactoryMethod(c => c.Resolve<ISessionFactory>().OpenSession()).LifeStyle.PerWebRequest);
could be quite hard.
So, should I try to make that abstraction? Any helpful resources?
Or should I just pick a IoC container and stick with it?
I could also make source code of an existing tool (Castle Windsor or Ninject) a part of my library, but I don't really understand those licenses. Can I do that? Can I change namespaces and class names to fit the structure of my app? I'm going to release the source code and I don't really care what the license is going to be.
It depends on what you mean by "hide." Best practice is that only one place in your application (the Composition Root) knows about the IoC container. Stick to the Hollywood Principle - avoid having multiple classes that know about the IoC container. In other words don't pass the container around; if a non-root class needs to create other objects then inject a factory into it.
If you're writing a framework and want to allow consumers to plug in their IoC container framework of choice, you could use the Common Service Locator library. That is likely overkill for most projects. (See Mark Seemann's excellent link for the reason I changed the wording).
Short answer - no, the abstraction is useless, you'd be wasting your employer's money. Use Installers to partition the registration instead.
I'm using the Unity IOC container and I'm just wondering what is the best best way to access the container for multiple classes.
Should every class have an IUnityContainer member and then pass the container in by constructor? Should there be a singleton class with an IOC container?
How about asp.net development?
Could somebody guide me in the right direction? Thanks.
IMHO it is not advisable to inject the entire container into a class or to have an application wide static IoC service locator.
You want to be able to see from the constructor of a class (lets call it Foo), what kind of services/objects it is using to get the work done. This improves clarity, testability and degubability.
Lets say Foo only needs the email service, but I pass in the whole container and somewhere in the code the email service gets resolved from the container. In this case it will be very hard to follow. Instead it is better to inject the email service directly to state Foo's dependencies clearer.
If Foo needs to create multiple instances of the email service, it is better to create and inject an EmailServiceFactory (via the IoC container), which will create the required instances on the fly.
In the latter case, Foo's dependencies are still indicated as specific as possible - only the ones, that the EmailServiceFactory can create. Had I injected the whole container, it would not be clear what services provided by it are Foo's exact dependencies.
Now, if I later want to provide different instances of the email service, I swap it out inside the EmailServiceFactory. I could swap out the whole factory as well, if all the services it creates need to be swapped (e.g. during testing).
So at the cost of creating one extra class (the factory), I get much cleaner code and won't have to worry about curious bugs that may occur when global statics are used. Additionally when supplying mocks for testing, I know exactly what mocks it needs and don't have to mock out an entire container's types.
This approach also has the advantage, that now, when a module is initialized (only applies to Prism / Modularity), it doesn't have to register all of the types of objects it supplies with the IoC container. Instead it can just register its ServiceFactory which then supplies those objects.
To be clear, the module's initialization class (implements IModule) should still receive the application wide IoC container in its constructor in order to supply services, that are consumed by other modules, but the container should not invade into the module's classes.
Finally, what we have here is another fine example of how an extra layer of indirection solves a problem.
Put the IOC container at the highest level / entry point in the process and use it to inject dependencies in everything underneath it.
you can register the container in itself and have it injected like every other dependency property, like so:
IUnityContainer container = new UnityContainer();
container.RegisterInstance<IUnityContainer>(container);
classes that need to access it will have the following property:
private IUnityContainer unityContainer;
[Dependency]
public IUnityContainer UnityContainer
{
get { return unityContainer; }
set { unityContainer = value; }
}
thus, the container is injected whenever an instance of such a class is resolved/built up.
This is more flexible as it works for multiple containers within the same application, which would not be possible with the singleton pattern.
If all of your objects need a reference to the container then you should look into reworking the code some. While still preferable to calling new everywhere it still scatters the responsibility of building your object graphs throughout your code. With that kind of usage it strikes me as being used more like a ServiceLocator instead of a IoC Container.
Another option would be using the CommonServiceLocator, although it may be a pointless indirection, you may use the ServiceLocator.Current as the instance known by all classes
I have a post on this subject at my blog where I´m using something along the lines of t3mujin answer. Feel free to use it (don´t bother that it´s sharepoint related...that doesn´t matter):
http://johanleino.spaces.live.com/blog/cns!6BE273C70C45B5D1!213.entry