ASP .NET Web API Queryable capabilities with deferred execution - odata

Should my api method always tie up to the underlying datasource (datacontext of an ORM) to expose Queryable capabilities supporting oData with the benefit of Deferred Execution?
Snippet
public class ProductController : ApiController {
public IQueryable<Product> Get() {
var dbContext = new DBContext();
return dbContext.Product.AsQueryable();
}
}
If I have to tie the always then, how and where can I apply business validation if I have to ? Eg: I want to return on the Products which are not expired.
Aren't we violating the seperation of concerns and doing tight coupling by exposing the data entities directly?

You can have the rule applied as below:
return dbContext.Product.Where(p=> !p.IsExpired).AsQueryable();
With regard to your second question, it is up to you. If you need to expose your data, then you should. If you want to expose an alternate view of the data, you can create a ViewModel and expose that.

Related

WebAPI ODATA -- Consuming With MVC Using Standard Controller/Ioc/Repository/UoW Sort of Architecture

Working with WebAPI ODATA services with javascript is not a problem... but what is a current recommendation to wrap the http calls (CRUD) to be consumed through a MVC5 application with a repository. Much of the guidance I see ultimately goes directly to the entity/dbcontext. I am looking for guidance which demonstrates the "drinking of your own Kool-Aid" and consuming the same ODATA (and it can be plain WebAPI, also) published externally to consumers of an application.
In my mind, I'm looking at this sort of flow:
AppController (site1:443)-->AppRepository-->OdataController (apiSite2:443)-->OdataRepository-->DataSource
The secondary concern is that I don't necessarily want direct access to a datasource by any consumer--especially posts without being vetted and I don't want all (any) of the logic in the controller. I might be overthinking something...
In order to extract the business logic from the controller I typically either push said logic down to domain objects whenever possible. If that isn't possible, then I'll create a class specifically designed to manage the logic in question, such as an interaction between two different objects.
If all else fails, then I'll have the interaction managed by a service. The classes might look something like the following:
public class SomeApiController : ApiController
{
public SomeApiController(ISomeApiService service)
{
this.Service = service;
}
private ISomeApiService Service { get; set; }
public IHttpActionResult SomeMethod(int someObjectId)
{
// service manages the logic and either defers to the object in question or resolves it through some specialized class
var result = this.Service.SomeMethod(someObjectId);
return this.OK(result);
}
}
public class SomeApiService : ISomeApiService
{
public SomeApiService(ISomeRepository repository)
{
this.Repository = repository;
}
private ISomeRepository Repository { get; set; }
}
... and so on.
The idea being that the layers have no dependencies upon one another which cannot be resolved through the IoC container of your choice and that the dependencies only go one way. That is to say SomeApiService has no dependency on SomeApiController and SomeApiRepository would have no dependency on SomeApiService.

better organise database operation codes in mvc

I am new to .net mvc ,and here is my situation, in mvc solution, I have data modal and reposity,also have ioc container, when comes to operate data operation,should I put all my logical code in the controller?or there are any better way?
public ActionResult SomeOperate(Person person)
{
var reposity = _kernel.Get<IReposity<Person>>();
//what about if there are many database operation logical based on my generic reposity,should I put them all here?
return RedirectToAction("SomeWhere");
}
EDIT1
my generic reposity have already support basic database operations such as add,update,remove,query transaction
By default, the controller can contain business logic (and its okay). But as your application grows in size, you start doubting whether the controller should be responsible for containing the business logic.
In a more advance architecture, the Controller only acts as a "Coach" and let players do the job. In other words, the controller only worries about who should do what. Hence the name controller.
The Service Layer
The Service Layer is just a collection of classes created for one purpose, to encapsulate your business layer, moving the logic away from the controller.
See my example below for a basic implementation of a service.
Service
public class ProductService
{
private IProductRepository productRepository;
public ProductService(IProductRepository productRepository)
{
this.productRepository = productRepository;
}
public IEnumerable<Product> ListProducts()
{
return this.productRepository.ListProducts();
}
public void CreateProduct(Product productToCreate)
{
// Do validations here.
// Do database operation.
this.productRepository.Create(productToCreate);
}
}
Controller
// Controller
public class ProductController : Controller
{
private ProductService productService;
// If you are wondering how to instantiate this
// controller, see the ninject tutorial
// http://www.codeproject.com/Articles/412383/Dependency-Injection-in-asp-net-mvc4-and-webapi-us
public ProductController(ProductService productService)
{
this.productService = productService;
}
public ActionResult Index()
{
IEnumerable<Product> products = this.productService.ListProducts();
return View(products);
}
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult Create(Product productToCreate)
{
if(!ModelState.IsValid)
{
return View();
}
this.productService.Create(productToCreate);
return RedirectToAction("Index");
}
The full tutorial straight from Microsoft: http://www.asp.net/mvc/tutorials/older-versions/models-(data)/validating-with-a-service-layer-cs
UPDATE
Why use a service layer
https://softwareengineering.stackexchange.com/questions/162399/how-essential-is-it-to-make-a-service-layer
Service per Model/Entity
With regards to the number of service per model, there is no absolute rule. Most of the time it can scale to one-to-one and sometimes one-to-many (referred service per module)
The number routines in a single service class depends on the number of operations in the UI, meaning if there is no delete button anywhere in the system then there shouldn't be a delete method anywhere in your code. In other words, CRUD should only apply when needed.
Service per Module
Sometimes a service can scale to multiple models, given there is an operation that requires you to updated multiple models. This is sometimes referred as "service per module", this is when a service does not represent a model but rather an operation.
RetireService
- RetireEmployee(User user)
MailingService
- SendWeeklyMails()
Services and Interfaces
Most of the time, interfaces are not required for a service layer. The only time that they are usually for the following reasons:
Large team (5 or more)
Large system
Heavy test driven development.
This link extends much on this subject:
https://softwareengineering.stackexchange.com/questions/159813/do-i-need-to-use-an-interface-when-only-one-class-will-ever-implement-it
The Single-Responsibility Principle would indicate that you should identify one responsibility for each class, and avoid putting logic into the class that doesn't pertain to that responsibility.
If this is just an exercise in learning technologies, or a small project, then you're probably safe putting most of your Entity manipulations and business logic in the individual controller actions. If this project is likely to grow, and need to be maintained by various people over time, you're probably better off defining an N-Tier architecture right off the bat.
How you do this will depend somewhat on personal preference and the nature of your project, but a popular approach is to create a "Service" or "Manager" layer where all of your business logic resides. Then the various controller actions invoke the actions on that layer, transform them into ViewModel objects, and pass them off to the views. In this architecture, Controllers end up begin very light-weight, and are focused mostly on transforming requests into service calls and composing the data that the Views will need to render.
Many people feel that the ORM (e.g. Entity Framework) represents the "data access layer," and they don't see a need to create an additional layer beyond the service layer. Other people create individualized classes to hold the queries and commands to Entity Framework, and the Service layer leverages these various other classes.

Repository Pattern Design for a ASP MVC app

This is more of a design concern.
Im building an app and i have created my Repository Pattern Structure as following :
My Core name space is the DAL/Repository/BusinessLogic layers assembly.
By the way, i am using Dapper.NET micro ORM as my data connection, thats why you will see an extension on my SqlConnection object.
For my data access, i have created a base repository class :
namespace Core
{
public class BaseRepository<T>: IDisposable where T : BaseEntity
{
protected SqlConnection conn = null;
#region Constructors
public BaseRepository() : this("LOCAL")
{
}
public BaseRepository(string configurationKey = "LOCAL")
{
conn = new SqlConnection(ConfigurationManager.ConnectionStrings[configurationKey].ConnectionString);
}
#endregion
#region IDisposable
public void Dispose()
{
conn.Dispose();
}
#endregion
/// <summary>
/// returns a list of entities
/// </summary>
/// <typeparam name="T">BaseEntity type</typeparam>
/// <param name="sproc">optional parameters, stored procedure name.</param>
/// <returns>BaseEntity</returns>
protected virtual IEnumerable<T> GetListEntity(string sproc = null)
{
string storedProcName = string.Empty;
if (sproc == null)
{
storedProcName = "[dbo].sp_GetList_" + typeof(T).ToString().Replace("Core.",string.Empty);
}
else
{
storedProcName = sproc;
}
IEnumerable<T> items = new List<T>();
try
{
conn.Open();
items = conn.Query<T>(storedProcName,
commandType: CommandType.StoredProcedure);
conn.Close();
}
finally
{
conn.Close();
}
return items;
}
}
}
And for each entity that I have, lets say ExtendedUser, Messages , i am creating its on Interface-Class pair like this :
namespace Core
{
public class ExtendedUserRepository : BaseRepository<UsersExtended>,IExtendedUserRepository
{
public ExtendedUserRepository() : this("PROD")
{
}
public ExtendedUserRepository(string configurationKey) : base(configurationKey)
{
}
public UsersExtended GetExtendedUser(string username)
{
var list = GetListEntity().SingleOrDefault(u => u.Username == username);
return list;
}
public UsersExtended GetExtendedUser(Guid userid)
{
throw new NotImplementedException();
}
public List<UsersExtended> GetListExtendedUser()
{
throw new NotImplementedException();
}
}
}
etc.
The above code is just one of the entities :ExtendedUser.
The question is : should i create a Interface-ClassThatImplemenetsInterface pair for each entity that i have ? or should i have only one RepositoryClass and one IRepository interface with all my methods from all of my entities?
I don't think you need to create interface without the reason. I even don't see why you need base repository class here. I even think this is not repository but DAL (Data Access Layer) but this is defintion argue.
I think good DAL implementation should decouple database structure from business logic structure - but hardcoding sp_GetList_XXXEntityNameXXX pattern or passing stored procedure name outside of DAL is not decoupling.
You are very optimistic or your application is really simple if you think all entity lists are obtained in one way and you will always need full set of entities in business logic without any parameters.
Separating interface from implementation is only needed if you plan to replace/wrap out different implementations, or mix few interfaces in one class. Otherwise it is not required.
Don't think in terms of entities when creating repositories. Repository contains business logic and should be built over scenarios of usage. Having classes like you have is more about Data Access Layer - and DAL is built over queries you would need in business logic. Probably you would never need list of ALL users at once - but would very often need list of active users, privileged users etc.
It is really hard to predict what queries you will need - so I prefer to start designing from business logic and add DAL methods by the way.
A system with a complex domain model often benefits from a layer, such
as the one provided by Data Mapper (165), that isolates domain objects
from details of the database access code. In such systems it can be
worthwhile to build another layer of abstraction over the mapping
layer where query construction code is concentrated.
http://martinfowler.com/eaaCatalog/repository.html
With a generic repository you can have common methods like findBy(array('id' => 1)), findOneBy(array('email' => 'john#bar.com')), findById(), findAll() and so on. Indeed, it'll have one interface.
You'll always have to create a concrete implementation that will indicates which is the domain object that will be managed by the repository in order to accomplish this getUsersRepository().findAll()
Moreover, if you need more complicated queries, you can create new methods on the concrete implementation, such as findMostActiveUsers() and then reuse it across your application.
Now, answering your question:
Your application will be expecting for at least one interface (that generic one, with the common methods). But if you manage to have specific methods, like the one I've just mentioned above, you'd be better having another interface (e.g. RepositoryInterface and UsersRepositoryInteface).
With that in mind, then you'll only depend on the repository interface. The query construction will be encapsulated by the concrete implementation. So you'll be able to change your repository implementation (e.g. using an full-blow ORM) without affecting the rest of your application.

Difference between Repository and Service Layer?

In OOP Design Patterns, what is the difference between the Repository Pattern and a Service Layer?
I am working on an ASP.NET MVC 3 app, and am trying to understand these design patterns, but my brain is just not getting it...yet!!
Repository Layer gives you additional level of abstraction over data access. Instead of writing
var context = new DatabaseContext();
return CreateObjectQuery<Type>().Where(t => t.ID == param).First();
to get a single item from database, you use repository interface
public interface IRepository<T>
{
IQueryable<T> List();
bool Create(T item);
bool Delete(int id);
T Get(int id);
bool SaveChanges();
}
and call Get(id). Repository layer exposes basic CRUD operations.
Service layer exposes business logic, which uses repository. Example service could look like:
public interface IUserService
{
User GetByUserName(string userName);
string GetUserNameByEmail(string email);
bool EditBasicUserData(User user);
User GetUserByID(int id);
bool DeleteUser(int id);
IQueryable<User> ListUsers();
bool ChangePassword(string userName, string newPassword);
bool SendPasswordReminder(string userName);
bool RegisterNewUser(RegisterNewUserModel model);
}
While List() method of repository returns all users, ListUsers() of IUserService could return only ones, user has access to.
In ASP.NET MVC + EF + SQL SERVER, I have this flow of communication:
Views <- Controllers -> Service layer -> Repository layer -> EF -> SQL Server
Service layer -> Repository layer -> EF This part operates on models.
Views <- Controllers -> Service layer This part operates on view models.
EDIT:
Example of flow for /Orders/ByClient/5 (we want to see order for specific client):
public class OrderController
{
private IOrderService _orderService;
public OrderController(IOrderService orderService)
{
_orderService = orderService; // injected by IOC container
}
public ActionResult ByClient(int id)
{
var model = _orderService.GetByClient(id);
return View(model);
}
}
This is interface for order service:
public interface IOrderService
{
OrdersByClientViewModel GetByClient(int id);
}
This interface returns view model:
public class OrdersByClientViewModel
{
CientViewModel Client { get; set; } //instead of ClientView, in simple project EF Client class could be used
IEnumerable<OrderViewModel> Orders { get; set; }
}
This is interface implementation. It uses model classes and repository to create view model:
public class OrderService : IOrderService
{
IRepository<Client> _clientRepository;
public OrderService(IRepository<Client> clientRepository)
{
_clientRepository = clientRepository; //injected
}
public OrdersByClientViewModel GetByClient(int id)
{
return _clientRepository.Get(id).Select(c =>
new OrdersByClientViewModel
{
Cient = new ClientViewModel { ...init with values from c...}
Orders = c.Orders.Select(o => new OrderViewModel { ...init with values from o...}
}
);
}
}
As Carnotaurus said the repository is responsible for mapping your data from the storage format to you business objects. It should handle both how to read and write data(delete, update too) from and to the storage.
The purpose of service layer on the other hand is to encapsulate business logic into a single place to promote code reuse and separations of concerns. What this typically means for me in practice when building Asp.net MVC sites is that I have this structure
[Controller] calls [Service(s)] who calls [repository(ies)]
One principle I have found useful is to keep logic to a minimum in controllers and repositories.
In controllers it is because it helps keeping me DRY. It's very common that I need to use the same filtering or logic somewhere else and if I placed it in the controller I can't reuse it.
In repositories it is because I want to be able to replace my storage(or ORM) when something better comes along. And if I have logic in the repository I need to rewrite this logic when I change the repository. If my repository only returns IQueryable and the service does the filtering on the other hand, I will only need to replace the mappings.
For example I recently replaced several of my Linq-To-Sql repositories with EF4 and those where I had stayed true to this principle could replaced in a matter of minutes. Where I had some logic it was a matter of hours instead.
The accepted answer (and upvoted hundreds of time) has a major flaw. I wanted to point this out in the comment but it will just get buried down there in 30 something comments so pointing out here.
I took over an enterprise application which was built that way and my initial reaction was WTH? ViewModels in service layer? I did not want to change the convention because years of development had gone into it so I continued with returning ViewModels. Boy it turned into a nightmare when we started using WPF. We (the team of devs) were always saying: which ViewModel? The real one (the one we wrote for the WPF) or the services one? They were written for a web application and even had IsReadOnly flag to disable edit in the UI. Major, major flaw and all because of one word: ViewModel!!
Before you make the same mistake, here are some more reasons in addition to my story above:
Returning a ViewModel from the service layer is a huge no no. That's like saying:
If you want to use these services you better be using MVVM and here is the ViewModel you need to use. Ouch!
The services are making the assumption they will be displayed in a UI somewhere. What if it is used by a non UI application such as web services or windows services?
That is not even a real ViewModel. A real ViewModel has observability, commands etc. That is just a POCO with a bad name. (See my story above for why names matter.)
The consuming application better be a presentation layer (ViewModels are used by this layer) and it better understand C#. Another Ouch!
Please, don't do that!
Repository layer is implemented to access the database and helps to extend the CRUD operations on the database. Whereas a service layer consists of the business logic of the application and may use the repository layer to implement certain logic involving the database. In an application, it is better to have a separate repository layer and service layer. Having separate repository and service layers make the code more modular and decouple the database from business logic.
Usually a repository is used as scaffolding to populate your entities - a service layer would go out and source a request. It is likely that you would put a repository under your service layer.

Service Layer are repeating my Repositories

I'm developing an application using asp.net mvc, NHibernate and DDD. I have a service layer that are used by controllers of my application. Everything are using Unity to inject dependencies (ISessionFactory in repositories, repositories in services and services in controllers) and works fine.
But, it's very common I need a method in service to get only object in my repository, like this (in service class):
public class ProductService {
private readonly IUnitOfWork _uow;
private readonly IProductRepository _productRepository;
public ProductService(IUnitOfWork unitOfWork, IProductRepository productRepository) {
this._uow = unitOfWork;
this._productRepository = productRepository;
}
/* this method should be exists in DDD ??? It's very common */
public Domain.Product Get(long key) {
return _productRepository.Get(key);
}
/* other common method... is correct by DDD ? */
public bool Delete(long key) {
usign (var tx = _uow.BeginTransaction()) {
try
{
_productRepository.Delete(key);
tx.Commit();
return true;
} catch {
tx.RollBack();
return false;
}
}
}
/* ... others methods ... */
}
This code is correct by DDD ? For each Service class I have a Repository, and for each service class need I do a method "Get" for an entity ?
Thanks guys
Cheers
Your ProductService doesn't look like it followed Domain-Driven Design principles. If I understand it correctly, it is a part of Application layer between Presentation and Domain. If so, the methods on ProductService should have business meaning with regard to products.
Let's talk about deleting products. Is it as simple as executing delete on the database (NHibernate, or whatever?) I think it is not. What about orders which reference the to-be-deleted product? And so on and so forth. Btw, Udi Dahan wrote a great article on deleting entities.
Bottom line is, if your application is so simple that services do really replicate your repositories and contain only CRUD operations, you probably shouldn't do DDD, throw away your repositories and let services operate on entities (which would be simple data containers in that case).
On the other hand, if there is a complicated behavior (like the one with handling 'deleted' products), there is a point in going DDD path and I strongly advocate doing so.
PS. Despite which approach (DDD or not) you will eventually take I would encourage you to use some Aspect Oriented Programming to handle transaction and exception related stuff. You would end up with way to many methods such as DeleteProduct with same TX and exception handling code.
That looks correct from my perspective. I really didn't like repeating service and repository method names over and over in my asp.net MVC project, so I went for a generic repository approach/pattern. This means that I really only need one or two Get() methods in my repository to retrieve my objects. This is possible for me because I am using Entity Framework and I just have my repository's get() method return a IQueryable. Then I can just do the following:
Product product = from p in _productRepository.Get() where p.Id == Id select p;
You can probably replicate this in NHibernate with linq -> NHibernate.
Edit: This works for DDD because this still allows me to interchange my DAL/repositories as long as the data library I am using (Nhibernate, EF, etc..) supports IQueryable.
I am not sure how to do a generic repository without IQueryable, but you might be able to use delegates/lambda functions to incorporate it.
Edit2: And just in case I didn't answer your question correctly, if you are asking if you are supposed to call your repository's Get() method from the service then yes, that is the correct DDD design as well. The reason is that the service layer is supposed to handle all your business logic, so it decides exactly how and what data to retrieve (for example, do you want it in alphabetical order, unordered, etc...). It also means that it can perform validation after loading if needed or validation before deleting and/or saving.
This means that the service layer doesn't care exactly how that data is stored and retrieved, it only decides what data is stored and retrieved. It then calls on the repository to handle the request correctly and retrieve/store the data in the way the service layer tells it to. Thus you have correct separation of concerns.

Resources