Configuring different assembly search list per Unity container - c#

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

Related

Do I need to register concrete root types in Simple Injector?

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

What is self-binding in an IoC container?

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.

IoC - is it bad practice to load a container within an object created by IoC?

I'm working with Castle Windsor as an IoC. I'm looking at a bit of code written by a team member and I am trying to figure out what the best practice here would be. Something rings odd to me about the way this was written, but I don't have the experience to say what should be done.
There are two Castle configs (which is my first gripe, but to give a benefit of the doubt, let's say this is okay). Let's say: cfgMain and cfgSub.
There is a main class which is responsible for setting up the application and causing it to run. (It can be a class with a Main() or a Global.asax, doesn't matter). Let's say: MainClass.
There is also a DependentClass.
MainClass instantiates a CastleContainer and installs cfgMain into it, then Resolves DependentClass.
DependentClass creates another CastleContainer and installs cfgSub in it. This is what I have a problem with
It seems like having a hardcoded path to a config inside of a class which itself is created via IoC is a recipe for disaster. It also makes it very hard to unit test.
Call to action: What's the best practice here? Should all the configs be merged? What if there's a reason (read: need) to separate them?
Without the information on why there are two configurations, it is impossible to judge that.
But assuming there is a reason, both classes sound to be parts of the Composite Root, a place near the start of the application that wires up all container dependencies. The main class is the composition root for the first configuration, the dependant class for the second configuration. There is still nothing wrong.
I would say that resolving the dependant class with the first container makes no sense - the composite root is a concrete class and there is no reason to replace it. However, there could be another reason the container is used to instantiate it - dependencies. If the dependant class itself depends on other services, resolving it with the main configuration sounds like the only way to resolve these dependencies.
Ultimately, with no other information, I would say that (with all these assumptions) what you describe could possibly make sense.
However, I strongly recommend to review the need of two separate configurations and two separate composite roots. Sounds overcomplicated.

caliburn.micro, Bootstrapper and CompositionRoot

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)

Not understanding where to create IoC Containers in system architecture

Say I have the following 4 .net assemblies:
Winforms UI
Business Logic
SQL Server Data Access (implementing an IRepository)
Common Interfaces (definition of IRepository etc.)
My business logic (2) makes calls to the data access layer (3) through IRepository (defined in 4) using constructor dependency injection. However when I ceate a business object I need to pass in an actual repository. I do this by having a singleton class in my business logic layer return the currently in use concrete object implementing IRepository. I am coming to the conclusion that this is a bad thing, as my business logic layer now has to reference 3 as well as 4.
I think I need a IoC Container but the question is where I create/put it as it seems that wherever I create this (1 - UI)? will also need to hold a reference to 3 (SQL Server Data Access). Am I not just moving the problem rather than achieving actual decoupling?
Do I create the IoC Container in the UI. Or expose it through another new assembly.
(I'm using C#, .net 3.5 and AutoFac)
Thanks.
IoC container generally should be created in the host project (application entry point). For the Windows.Forms application that's the exe project.
Generally in simple solutions (under 10 projects), only a host project should have a reference to IoC library.
PS: Structuring .NET Applications with Autofac IoC
When registering components there are several possibilities:
Registration in code:
directly
Problem: you have to reference everything ( you are here)
indirectly
Problem : to find out what has to be registered
Solution:
use attributes
use marker interface as IService
use conventions (see StructureMap)
Registration with configuration file:
let the container do everything
read the file yourself
Top level is a way to go (UI, as Rinat said).
Now as for references, simplest way is just to go over all assemblies in the current folder and use some convention to get the services out. Attributes work fine, putting registrar classes in each assembly works fine, whatever suits you. The code for extracting everything should probably be in a separate assembly, unless your IoC framework already does that.
The module distinction and the "scopes" defined by the modules exist mostly at compile-time. In the run-time it's all one big mess ;) This is used by most IOC containers and they don't really care about where they are located. The IoC container for a web-app will typically be created at the outermost level (very close to the web-container itself).
It's true that you could create it anywhere, but I'd introduce an extra layer, let's call it 3.5.
Your current 3 would be where your IoC resides for Data Access - this would become a wrapper for your actual DAL. Based on your config, 3 would create either a mock repository or a concrete one.
So 2 still references 3, but it's just an interface to the actual DAL which is configured through your IoC framework.
Alternatively, you could roll your own 'el-cheapo' IoC - change your Big Ugly Singleton to a Static Gateway - Abstracting IoC Container Behind a Singleton - Doing it wrong?

Categories