I am designing an asp.net mvc application which uses a service layer. What if we have a service which depends on another service? For, instance, suppose we have the following model:
class UserService : IUserService
{
//implementation requires IEmailService
}
Sure, the concrete implementation EmailService can be injected into the constructor of UserService, but in my understanding, a service layer should mediate between UI and Domain Model, it's like a facade. I would define another layer in such a way that UserService depend on IUserModule and IEmailModule, in this way we could break the dependency between services, services being dependent on a lower layer (in my case module layer). Is it a correct approach?
Inside a common DDD architecture you'll find two kind of services Domain services (whose coordinate business operations among entities) and Application services (whose depend on the Domain services, and contain tasks related to the application and not to the business logic e.g. export to pdf is an application task. apply a discount is a business logic task).
So if you only have a kind of service, which I suppose covers both responsibilities. is totally valid to have interdependencies.
Sure, the concrete implementation EmailService can be injected into the constructor of
UserService, but in my understanding, a service layer should mediate between UI and Domain
Model
Well, it's a contract between to sides, not necessarily UI and Domain Model, but commonly.
it's like a facade.
Yes, a good service features a nice facade also accounting for performance.
this way we could break the dependency between services, services being dependent on a
lower layer (in my case module layer). Is it a correct approach?
What does module mean to you? Is IEmailService a service or a module to you? It seems correct to create the Facade in your case for your service. But you provide to few information about your system and your intent and your architectural challenges/priorities.
Dependency injection is something you should avoid as it increases coupling and complexity for an illusion of flexibility. MVC is also something to reconsider before you start your development because it is not good for anything more than simple applications that do CRUD operations. Web Forms is a more proven platform and is better for more usable applications.
Related
So, I've decided to use the Microsoft Extensibility Framework(MEF) with my new ASP.NET MVC web project. The project is a very typical employee management system, with 3 traditional layers :- a presentation layer (with views and controllers), a business layer (with business objects) and ofcourse, a data access layer. After some research, I read a lot, that MEF is supposed to help us implement the plug-in architecture.And this is where, I seem to get stuck. I'm not able to relate with this pluggable part. I'm pretty sure that, since MEF is the part of the core .NET framework, it is not limited to any specific kind of application, and is supposed to be useful in general. I just need to see my application structure in a new light, and that's where I need some helpful insights.
As I'm still trying to get started with MEF, my main question is; what would be the main extensible(pluggable) points in my application? What objects should one be typically composing using the MEF's compose method, and what would be the advantages of doing so using MEF instead of the traditional way?
MEF will not help you solve extensibility issues in the case you have described in the question, because it doesn't seem to have any. What MEF can bring to the table for this particular case is Dependency Injection. If you develop your application in a way that the presentation layer depends on business abstraction and the business layer depends on a data access abstraction rather than on concrete implementation, you will get a highly decoupled application that is easy to test, maintain and change without affecting unnecessary components. Here is one way to do this:
Lets say you have data access class that performs CRUD operations on employees:
[Export(typeof(IEmployeeRepository))]
public class EmployeeRepository : IEmployeeRepository
{
//Some logic here
}
As you can see the EmployeeRepository class implements IEmployeeRepository interface which adds the level of abstraction that is needed to develop a decoupled application. Now lets say that in the business layer you have a class that needs to call some method from the EmployeeRepository class. To be able to call a method of EmployeeRepository, you would need an instance of it. Without using MEF (or any other IoC framework, this would be a way to do it:
public class EmployeeManager
{
private EmployeeRepository _employeeRepository;
public EmployeeManager
{
_employeeRepository = new EmployeeRepository();
}
}
By using the above code sample, a hard dependency between the EmployeeManager and EmployeeRepository classes is created. This hard dependency is difficult to isolate when writing unit tests and causes any change of the EmployeeRepository class to directly affect the EmployeeManager class. By refactoring the code sample a little bit and putting MEF into the game, you'll get this:
[Export(typeof(IEmployeeManager))]
public class EmployeeManager : IEmployeeManager
{
private IEmployeeRepository _employeeRepository;
[ImportingConstructor]
public EmployeeManager(IEmployeeRepository employeeRepository)
{
_employeeRepository = employeeRepository;
}
}
As you can see the EmployeeManager class now doesn't depend on the EmployeeRepository class, but it depends on IEmployeeRepository interface, in other words it depends on abstraction. And it doesn't create the instance of EmployeeRepository class by itself. That job is left to MEF. By now it should be clear that export and ImportingConstructor attributes are part of MEF and are used by it to discover parts and resolve dependencies at runtime. With the last code sample the classes are decoupled, easy to test and maintain and you can change the internal logic in EmployeeRepository class without making EmployeeManager class aware of it. Of course the contract between them, IEmployeeRepository have to be maintained.
The above said, can be used to decouple the presentation layer from the business layer also. Also the above said, can be implemented by using any other IoC framework, like Ninject, Autofac, StructureMap etc. The difference between these IoC frameworks and MEF is that if you use them, you'll need to configure at application start which instance gets created when some interface is encountered:
//something like this, in the case of Ninject
this.Bind<IEmployeeRepository>().To<EmployeeRepository>();
On the other hand, MEF has the ability to discover parts at runtime. On application start, you'll just need to inform it where to look for parts: Directory, Assembly, Type etc. The auto-wire capabilities of MEF (the ability to discover parts at runtime), make it more than a regular IoC framework. This ability makes MEF great for developing pluggable and extensible applications because you'll be able to add plugins while the application is running. MEF is able load them and let the application to use them.
I'm sure someone has asked this before, but I'm struggling to find where.
I'm using Ninject to remove dependencies from my controllers, along with a repository design pattern.
As I understand it, one of the benefits of this approach is that I can easily whip apart my repositories and domain entities and use another assembly should I so wish. Consequently I've kept my domain entities and repositories in external assemblies and can mock all my dependencies from interfaces.
It seems that while I can use interfaces to refer to my domain entities in most places I must use references to my concrete classes when it comes to model binding. I've read that this is to do with serialization which I understand, but is the only way to avoid referring to domain entities to create separate models?
Anything I can do with Custom Model Binding?
A bit of background: I'm an experienced ASP.net developer, but new to MVC.
View Models should be plain data containers with no logic and therefore shouldn't have any dependencies at all. Instead inject the repositories to your controller and have it assign the required data from the repository to the appropriate property of your view model.
The major advantage of using a dependency injection framework is IoC (Inversion of Control):
loosely coupling
more flexibility
easier testing
So what one usually does is to inject repositories through their interfaces like
public class MyController : Controller
{
private IPersonRepository personRepo;
public MyController(IPersonRepository personRepo)
{
this.personRepo = personRepo;
}
...
}
During testing this allows to easily inject my mock repository which returns exactly those values I want to test.
Injecting domain entities doesn't make that much sense as they are more tightly linked with the functionality in the specific class/controller and thus abstracting them further would just be an overhead rather than being a benefit. Instead, if you want to decouple your actual entity model from the controller you might take a look at the MVVM pattern, creating specialized "ViewModels".
Just think in terms of testability of your controller: "What would I want to mock out to unit test it?"
DB accesses -> the repository
External dependencies -> other BL classes, WS calls etc.
I wouldn't include domain entities here as they're normally just a data container.
Some more details would help. A bit of code perhaps?
To start with, you should avoid injecting dependencies into domain entities, but rather use domain services.
Some more info here.
Edit 001:
I think we should clarify our terminology.
There is the domain layer with all you domain entities, e.g. product, category etc.
Then there's the Data Layer with your repositories that hydrate your domain entities and then you have a Service Layer with you application services that talks to the data layer.
Finally you have a presentation layer with your views and controllers. The Controllers talk to you Aplication Service Layer. So a Product Controller talks to a Catalogue Service (e.g. GetProductBySku). The CatalogueService will have one or more repositories injected into its constructor (IProductRepository, ICategoryRepository etc.).
It's quite common in asp.net mvc to have ViewModels too. Put the ViewModels in your Application Service Layer.
So I'm not sure what you mean when you say "models" and "domain enntities" but I hope that clears up the terminology.
I am about to start developing a medium sized ASP.Net MVC application.
I am trying to get the design right. I intend to have the following layers:
UI layer (MVC)
Service Layer
Repository Layer
Data Access Layer
I will be using Unity as my IOC container and EF4.1 Code First for Data Access.
The app will be split into several assemblies. I have a problem deciding which assemblies I will need
and where to put the following:
Entities/Domain objects e.g. Customer, Invoice
DTOs e.g. CustomerDTO, InvoiceDTO
Service interfaces e.g. ICustomerService
Repository Interfaces e.g. ICustomerRepository
Services(Service interface implementation classes) e.g. CustomerService
Repositories (Repository Service implementation classes) e.g. CustomerRepository
ViewModels e.g. CustomerViewModel
Enums
My question is:
How do you usually split yours and why?
Edit: prompted by the #TheHurt's answer.
How would the references be between the assemblies, i.e. which assembly would be referencing which?
This is how I might tackle it:
App.UI assembly:
ViewModels go in Models area.
App.Repository assembly:
Abstract implementation of concrete repository.
ICustomerRepository
App.Repository.SQL:
Concrete implementation.
EFCF POCOs
App.Services assembly:
Abstract service.
ICustomerService
DTOs
App.Services.Implementation:
Concrete service.
CustomerService
App.Common:
Shared code.
Enums
There are a couple issues that I still struggle with. You lose the data annotations from EFCF when you cross the services boundary. So then you have to do server side validation or you have to keep your view models validation in sync with the repository entities. It feels that the more layered things are, the more DRY is violated. I suppose that is par for the course though when your view models don't map to your entities directly. You could have your view models be your DTOs and toss them into the Common assembly, but that seems to couple things too tightly if you have the need to be super flexible with your services.
EDIT
If you are wanting to integrate WCF into the mix you would probably want to create data contracts that are very close to the MVC view model (or use the contracts as the view model). You probably wouldn't expose that to the world as the service would be specific to that implementation of your MVC site, spin up another service for public consumption. If you are doing a WCF service you probably want to have all of your business logic in the service, the controllers would just handle navigation logic.
Side note, I try to stay away from the "metal" as much as possible, while developing a design that will allow me to separate the code into various layers in the future. If I cannot clearly explain the various system layers to my manager with one sheet of paper, the design is more than likely too complex. Everything for the most part will look pretty in Visio if it is designed well.
As far as how things reference each other: UI would ref the Serivce (or service implementation, which may not be needed. Just keep it all in the same place.). Service refs the Repository. The repository implementation refs nothing, since it is loaded by IOC. Everything refs Common.
When I start work on a new web application I tend to reach for the same tried & tested architecture of ASP.NET MVC, BLL (consisting of a set of services that contain all business logic) and a DAL (consisting of a set of repositories that facilitate the unit of work pattern over something like EF/*Linq to SQL*).
The controllers talk only to services, the services only to repositories and other services. At the service layer are where models are defined and these are used as input/output to/from the controllers.
My question is: what are others doing? I'm interested in knowing if people are doing anything different in the context of an ASP.NET MVC web application. For instance, there are concepts like CQRS and Domain Events. Is anyone using these to solve a problem with the method I've described above?
This question is mainly a source of attempting to discover what I don't know I don't know. I hope it's not too vague, but I think it's important to see what others are doing to evaluate your own methods.
We're basically doing what you're doing, except that we consider our repository interfaces to be services (they are defined in the business layer), and therefore our controllers often access them directly. An IoC container takes care of injecting the correct repository implementation via constructor injection. So the data layer depends on the business layer, and is in charge of implementing the repositories, while the business layer just assumes that all the repositories it has defined will be available at runtime.
We've further divided our product up into different modules of functionality. Some of the modules depend on one another (for example, everything depends on our core functionality, and most of the other modules depend on the web portal module), but keeping them in separate dlls helps us to avoid making these modules be too tightly coupled. The system can therefore only load the DLLs for the modules that a given client has paid for. We plan to use an event bus with events defined in the core module to allow the modules to communicate via a publish/subscribe model.
I am using CQRS with MVC. Its nice. You still use the MVC pattern, but in the controller I use the command pattern for the write, and just pure NHibernate Linq for the read... also some SolrNet for the read. :-)
I'm looking for some feedback on my ASP.NET MVC based CMS application architecture.
Domain Model - depends on nothing but the System classes to define types. For now, mostly anemic.
Repository Layer - abstracted data access, only called by the services layer
Services Layer - performs business logic on domain models. Exposes view models to the controllers.
ViewModelMapper - service that translates back and forth between view models and domain models
Controllers - super thin "traffic cop" style functionality that interacts with the service layer and only talks in terms of view models, never domain models
My domain model is mostly used as data transfer (DTO) objects and has minimal logic at the moment. I'm finding this is nice because it depends on nothing (not even classes in the services layer).
The services layer is a bit tricky... I only want the controllers to have access to viewmodels for ease of GUI programming. However, some of the services need to talk to each other. For example, I have an eventing service that notifies other listener services when content is tagged, when blog posts are created, etc. Currently, the methods that take domain models as inputs or return them are marked internal so they can't be used by the controllers.
Sounds like overkill? Not enough abstraction? I'm mainly doing this as a learning exercise in being strict about architecture, not for an actual product, so please no feedback along the lines of "right depends on what you want to do".
thanks!
Overall, the design looks good to me.
There are a few more items I might do:
Validations - have a 2 step validation -
Step 1 : the domain-level classes enforce their own validity (via attributes or any other mechanism).
Step 2: The repository ensures that the object is valid in the context of the repository
Dependency Injection - use a DI framework to inject dependencies. It will be useful for unit testing. Also, If the service layer where you need to call across services, check if this article on Aggregate Service is useful: http://blog.ploeh.dk/2010/02/02/RefactoringToAggregateServices.aspx
ViewModels - might be tempting to re-use, but wait & watch before you finally decide
HTH.