StructureMap DI on Model Assembly - c#

I’m new to Dependency Injection and had a question/need guidance.
I had an application that used the repository pattern for data access. I used StructureMap to get the correct repository and all worked well.
I have since broken out my model (including the repository logic) into its own assembly and added a service layer. In the interest of DI the service layer class takes an IRepository in its constructor. This seems wrong to me as now all consumers of my model need to know about the repository (at least configure their DI to know which one to use). I feel like that is getting into the guts of the model.
What sounds wrong with this?

An application written to use dependency injection typically configures a single container instance where all the interface/implementation type mappings have been registered at an initialization stage of the application. This would include the registration of the repositories, services, and any consumers of the service within the application.
By resolving the consumers of the service through the container, consumers need only indicate their dependency upon the service, not any dependencies the service might need. Therefore, the consumers of the service will not be coupled to its dependencies (e.g. your repository). This is the benefit of doing dependency injection through a container as opposed to doing manual dependency injection.
If you are designing services to be consumed by other applications in the form of a reusable library then your options will vary depending on the level of flexibility you wish to offer.
If you presume all clients of your library will be using dependency injection, then you will need to provide an appropriate amount of documentation about what types need to be registered within their container.
If you presume all clients will be using a specific container (e.g. StructureMap), then you can ease the registration requirements by providing registries which encapsulate all the specific registration needs for the client.
If you wish to allow your library to be used by clients not using their own dependency injection container then you can provide a static factory which returns the service. Depending on the level of complexity, such a scenario may not require use of a container (for example, if your service is comprised by just a few objects in all). If your library is comprised of a substantial amount of components which need to be composed then you might have factories which resolve the services through their own shared internal infrastructure initialization needs.

I understand your dilemma there Dan, I too spent lots of time wrestling over that in my mind. I believe the way I decided to go forward with was one of best ways to encapsulate all of the concerns and still have easily maintainable loosely coupled objects.
I wrote this blog post specifically about NHiberante but if you look at the repository pattern in implement you can easily change the NH specific code to use your backingstore.
Creating a common generic and extensible NHiberate Repository

Related

Modern Layered Architecture Implementation

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.

Autofac IoC factories abstraction

My application uses autofac IoC. It contains a layer that establishes connections to external applications (creating "Protocol" objects) - Therefore, I realized from my previous question that I should use autofac factory:
Autofac resolve in deep layer
I have a side project that includes all the autofac nugets and dlls. This one provides specific API which I use to register types in my application:
RegisterType
RegisterTypeAndAutowireProperties
RegisterConfigurationObject
RegisterInstance
BuildContainer
UpdateContainer
I believe this API is generic and fits for any application that will want to make use of IoC container.
My problem is with the factories. For example in my current application I need a factory for protocols (which are keyed and depend on many keyed services as well). Each protocol object is taking different kind and number of services and therefore I don't have a way other than making an explicit method for each protocol registration if I'm correct.
Now what happens in the next application that'll want to use this IoC API? It might not have the protocols this application contains, a case which will force me to update the IoC API for each application. Is there a way to keep my IoC wrapper generic - make it fit for any application no matter that types it contains? If you have any ideas in mind please share them with me!
Thank you
Edit:
I'll try to make it clearer, I use Autofac only. This "wrapper" is a project with the references to autofac that supplies basic API of IoC. For now I use this project only in application1.
But If tomorrow I start developing application2 I want to use this same wrapper. Therefore I can't have factories in my wrapper project that fit for a specific application. This is my issue

Can ninject be used to configure class based inject (instead of interface)?

Can Ninject be used to configure non-interfaced based injection?
public EntityController([Named("EntityServiceName")] EntityService service)
instead of
public EntityController([Named("EntityServiceName")] IEntityService service)
I'm trying to do just this and running into problems, and was wondering if the issue was that I'm not using interfaces.
Additional info:
Maybe I'm off here, but here is the benefit we're hoping for:
We're following a DDD pattern with an onion/ports and adapters architecture, so we have a domain project with concrete domain objects and domain services as well as external interfaces defined, an infrastructure project which implements the external interfaces defined in the domain, and finally a web api project for exposing them.
The controllers of the web api need to have an instance of the domain services injected into them. But since there would be a 1:1 relationship between the interface and the domain service, it seems like unnecessary bloat to just add interfaces for the domain services.
So there is really no benefit to making an interface for the domain services, but I would still like to configure and inject them via Ninject.
You can... yes. But there's not much it accomplishes. Here's an example:
kernel.Bind<List<string>>().ToConstant(new List<string>(){"Foo", "Bar"});
But if you're not using an Interface, you're not really getting much benefit of Dependency Injection. And obviously this accomplishes nothing over ICollection. I suppose you could use it to set default class values, and still get the advantage of unit testing... but doing so with Interfaces will usually be much better, since you can do much better mocking. I would only do this for the most basic of classes.

Can I register all IoC container components in single layer, or each layer where used?

I'm using the Unity IoC framework and have a Bootstrapper.cs class in my host MVC layer to register all components. However in my architecture I have a 'services' layer below the MVC layer, that too uses DI and there are repository interfaces injected into it (repository interfaces are not used in the MVC layer - it has the services layer Interface injected into its Controllers).
So my question is the following: can I still register the repository interface to it's concrete type in the MVC/UI layer for the entire app, or do I add another reference to Unity and create another Bootstrapper.cs class in my 'services' layer to define Interface types for that that specific layer uses?
Even if the answer is I can register the Interface in the UI layer, I'd still like to know the common practice too. The thing I don't like about registering that type in the MVC/UI layer is I would have to add a reference to the Repository layer just to make the registration, even know it is not used in that layer. It's used in the services layer.
Thanks!
Each application should have its own Composition Root, the place where you configure the application (see this answer for details).
It depends on the context, but generally speaking, if you split your container configuration among the layers you are going to make decisions about the configuration of your layers too close to the layers and you'are likely to lose the general view.
For example, in one of your business logic layers you'are registering a service:
container.RegisterType<ISercice1, MyImplementation1>(new PerThreadLifetime())
But when using that layer in a web application you could decide that a PerSession or PerRequest lifetime would be better lifetimes. This decisions should be in only one place and not spread through the layers.
I turn your question on its head.
If you add a reference to Unity in your class libraries, you would have added dependencies to the framework you are using. That is quite the opposite of what you are trying to achieve.
The only adaptation your classes should need is to support constructors or using public properties - on interfaces. That's it!
So your application entry point should do all the 'bootstrapping'.
Note that a entry point could be different applications, as well as different test projects. They could have different configurations and mocking scenarios.
If your bootstrap.cs gets large, you could split it up into smaller parts for readability reasons. But I reject the idea of classes having any knowledge about the fact that they are being bootstrapped/moqed/injected and by what.
Consider re-use. Your current libraries is using Unity. They may be used in a project using StructureMap. Or why not Ninject.
In short, yes it is possible to keep the configuration at the top of the process or localized to each module. However, all dependencies must be resolved for the entire object graph in the process.
Localizing the configuration by keeping it in each module (assembly) is often a good idea because you are allowing your service layer to take responsibility for its own configuration. My answer to this question, IMHO, is a good practice.
Yes, application should have one composition root at entry point. But it can be a good practice to keep registrations of a classes inside a layer where they are implemented. Then pull these registrations from layers at composition root, registering implementations layer by layer. This is why:
Registration within layer can be redefined in other place, for
example at entry point. Most of IoC libraries work in such a way
that registration done later erases the registration done earlier.
So registration within layer defines just a default behavior which
can be easily overridden.
You don't need to reference IoC library in all your projects\layers, even if you have registrations defined inside these
layers. A very simple set of wrapper classes will allow you to
abstract away from IoC specifics anywhere except your entry point.
When your application has several entry points, reusable registration will greatly help to prevent repeating the same
registration. This copy\paste is always bad. And applications have
several entry points quite often. For example, consider the scenario
of cross-platform application having a separate entry point for
every platform it targets. Or business logic reused in web site and
in background process.
With reusable registration, you can build a very effective testing system. You will be able to run a whole layer from tests,
mock whole layers in automated way, and do it very effectively,
minimizing efforts on writing tests.
See my blog article illustrating these points in more detail, with a working sample.

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