Modern Layered Architecture Implementation - c#

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.

Related

Should I separate IoC binding seperation by project

I am new at domain driven design architecture. My project solution is like this:
Presentation(Web)
ApplicationLayer
QueryLayer
QueryHandlerLayer
DataLayer
I read from articles theese separations is doing to isolate jobs.
Presentation project references ApplicationLayer
But does not reference QueryLayer,QueryHandlerLayer and DataLayer.
But I am using IoC container and bind types to interface.
container.Bind(data interfaces).To(data classes);
container.Bind(query interfaces).To(query classes);
I can do this on PresentationLayer. But now all projects will be add reference to presentation layer.
Is this an issue about architecture? Or May I separated IoC container binding for all layers?
Using DI is about composing applications. An application might have multiple layers, but they are still part of the same application and must be composed together.
The appropriate place to compose an application is in the composition root, which should be as close to the entry point of the application as possible.
There are basically 3 common recommendations for composing applications with multiple layers, and all of them are perfectly acceptable.
Don't separate the layers into physical assemblies.
Compose the application in the presentation layer, and reference all other layers from the presentation layer.
Create a separate composition layer that references all of the other layers.
For the 3rd option, you should keep in mind that the composition layer is supposed to drive, not be driven by, the rest of the application.
See this answer for the reasoning behind this referencing and why it is important that you do reference every library from the composition root to avoid tight coupling. Or, as mentioned, you could use late binding to compose your application without referencing the assemblies directly, provided your deployment script copies over the DLLs.
I think the biggest thing I have learnt in recent usage is that at the fundamental level, DI is about Injecting Dependancies. That's a pretty redundant description, so let me elaborate:
DI starts with design. Everything should have what it needs provided to it via a constructor, or factory of some sort. This is where Interfaces are your best friend. Once you have done this, most of the work is done. Assuming some of the projects are shared, you have now delegated out all of the work to whoever is using it. This is probably old news, however.
Next, if you are in control of the container, consider creating a default module, which in the case of Ninject is a, NinjectModule. Create one of these for each application layer. This will form the "instructions" so to speak, for the container at the highest level of your program to put all the pieces together.
This can all be loaded by reflection trickery of which there is plenty of information around, like this.
Then it is as simple as loading all of these binding "instruction manuals" into the composition root (usually in the application) and you're good to go.

3 Tier Architecture with NHibernate, Ninject and Windows Forms

So I'm in the middle of rafactoring a small to medium sized Windows Forms application backed by a SQLite database accessed through NHibernate. The current solution contains only an App Project and Lib Project so it is not very well structured and tightly coupled in many places.
I started off with a structure like in this answer but ran into some problems down the road.
DB initialization:
Since the code building the NHibernate SessionFactory is in the DAL and I need to inject an ISession into my repositories, I need to reference the DAL and NHibernate in my Forms project directly to be able to set up the DI with Ninject (which should be done in the App Project / Presentation Layer right?)
Isn't that one of the things I try to avoid with such an architecture?
In an ideal world which projects should reference eachother?
DI in general:
I have a decently hard time figuring out how to do DI properly. I read about using a composition root to only have one place where the Ninject container is directly used but that doesn't really play well with the current way NHibernate Sessions are used.
We have a MainForm which is obviously the applications entry point and keeps one Session during its whole lifetime. In addition the user can open multiple SubForms (mostly but not exclusively) for editing single entities) which currently each have a separate Session with a shorter lifetime. This is accomplished with a static Helper exposing the SessionFactory and opening new Sessions as required.
Is there another way of using DI with Windows Forms besides the composition root pattern?
How can I make use of Ninjects capabilites to do scoped injection to manage my NHibernate Sessions on a per-form basis (if possible at all)?
Terminology:
I got a little confused as to what is a Repository versus a Service. One comment on the posted answer states "it is ok for the repository to contain business-logic, you can just call it a service in this case". It felt a little useless with our repositories only containing basic CRUD operations when we often wanted to push filtering etc. into the database. So we went ahead and extended the repositories with methods like GetByName or more complex GetAssignmentCandidates. It felt appropiate since the implementations are in the Business Layer but they are still called repositories. Also we went with Controllers for classes interacting directly with UI elements but I think that name is more common in the Web world.
Should our Repositories actually be called Services?
Sorry for the wall of text. Any answers would be greatly appreciated!
Regarding 1:
Yes and no. Yes you would prefer the UI Layer not to be dependent on some specifics of x-layers down. But it isn't. The composition root is just residing in the same assembly, logically it's not the same layer.
Regarding 2:
Limit the usage of the container. Factories (for Sessions,..) are sometimes necessary. Using static should be avoided. Some Frameworks however prevent you from using the ideal design. In that case try to approximate as much as possible.
If you can currently do new FooForm() then you can replace this by DI or a DI Factory (p.Ex. ninject.extensions.Factory). If you have absolutely no control on how a type is instanciated then you'll need to use static to access the kernel like a service locator and then "locate" direct dependencies (while indirect dependencies are injected into direct dependencies by the DI container).
Regarding 3: i think this is somewhat controversial and probably often missunderstood. I don't think it's really that important what you call your classes (of course it is, but consistency across your code base is more important than deciding whether to name them all Repository or Service), what's important is how you design their responsibilities and relationships.
As such i myself prefer to extract filters and stuff in the -Query named classes, each providing exactly one method. But others have other preferences... i think there's been enough blog posts etc. on this topic that there's no use in rehashing this here.
Best practice to implement for situation like yours is to use MVP design pattern. Here its the architecture that i can offer to you.
MyApp.Infrastructure // Base Layer - No reference
MyApp.Models // Domain Layer - Reference to Infrastructure
MyApp.Presenter // Acts like controllers in MVC - Reference to Service, Models,
MyApp.Repository.NH // DAL layer - Reference to Models, Infrastructure
MyApp.Services // BLL Layer - Reference to Repository, Models
MyApp.Services.Cache // Cached BLL Layer(Extremely recommended) - Reference to Services, Models
MyApp.UI.Web.WebForms // UI Layer - Reference to all of layers
I will try to do my best to explain with the example of basic implementation of 'Category' model.
-Infrastructure-
EntityBase.cs
BussinesRule.cs
IEntity.cs
IRepository.cs
-Models-
Categories(Folder)
Category.cs // Implements IEntity and derives from EntityBase
ICategoryRepository.cs // Implements IRepository
-Presenter-
Interfaces
IHomeView.cs // Put every property and methods you need.
ICategoryPresenter.cs
Implementations
CategoryPresenter.cs // Implements ICategoryPresenter
CategoryPresenter(IHomeView view, ICategorySevice categorySevice){
}
-Repository-
Repositories(Folder)
GenricRepository.cs // Implements IRepository
CategoryRepository : Implements ICategoryRepository and derives from GenricRepository
-Services-
Interfaces
ICategorySevice.cs
AddCategory(Category model);
Implementations
CategorySevice.cs // Implements ICategorySevice
CategorySevice(ICategoryRepository categoryRepository ){}
AddCategory(Category model){
// Do staff by ICategoryRepository implementation.
}
-Services.Cache-
// It all depents of your choose.. Radis or Web cache..
-UI.Web.WebForms-
Views - Home(Folder) // Implement a structure like in MVC views.
Index.aspx // Implements IHomeView
Page_Init(){
// Get instance of Presenter
var categoryPresenter = CategoryPresenter(this, new CategorySevice);
}
I'm not sure if i got your question correct, but maybe give you an idea:)

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.

StructureMap DI on Model Assembly

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

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