Mocking NHibernate & Linq - c#

I'm using NHibernate and exposed the Session in my front end. I have a controller action which retrieves tasks as follows:
public ActionResult Overview(DateTime date)
{
var allTasks = GetTasksUpUntilDate(date);
return PartialView("Tasks/Overview", allTasks);
}
private List<TaskOverviewModel> GetTasksUpUntilDate(DateTime date)
{
var allTasks = _session.Query<Task>().Where(t.BookedBy.UserName.Equals(CurrentUser.Name,
StringComparison.CurrentCultureIgnoreCase));
var tasks = allTasks.Where(t => t.DueDate <= date);
var taskVMs = new List<TaskOverviewModel>();
tasks.ForEach(t => taskVMs.Add(MapEntityToViewModel(t)));
return taskVMs;
}
Now I don't want to create an IRepository just for my views since ISession actually already is a repository. Mocking/stubbing this however is proving rather hard. So can anyone help me to have _session.Query return a list of objects I provide while testing?.
I'd also like to avoid setting up an in memory database and am using RhinoMocks for my tests.

Dont fake Nh/linq. Instead setup an in-memory sqlite db to query against. They are extremely fast and easy to use.

NHibernate Session might fit the repository pattern, but if you are building your controllers to talk to it directly, you are not truly abstracting it. Mocking it when you aren't abstracting it is not a reliable solution.
If you absolutely don't want to abstract it (which is pure lazy, IMO), then the sqllite db as mentioned by Jason is a good call. However, on a large project properly separating your concerns is very much a good idea.
My domain model contains the interfaces for both the data access objects (repos) and the services which consume them. This allows me to truly separate my data concerns from my business concerns, which should be entirely separated from the view/app concerns. This allows proper unit testing and the ability to easily swap out parts or do proper mocking.
Each layer ONLY talks to interfaces, NEVER to an implementation. Furthermore my application layer never talks directly to the data layer - only services. Allowing that to happen seems to encourage developers to be lazy and start putting business or data logic into the application.

Related

confusion in understanding of repository pattern

Im new in MVC pattern but im involved in a project which i am asked to implement repository pattern and unit of work,tons of examples online with 100 different implementations thats also a pain,because there is no clear way,any way,here is what i am doing and i would like you to give me a reason why should i use this damn pattern:
i have many controllers i instantiate the the model,and use it in my controller:
public CentralEntities DB = new CentralEntities();
i use it in my controller for example like this:
var turbineid = (from s in DB.MasterDatas
where s.name == turbinename
select new TrBineId
{
turbineID = s.m_turbine_id
}).Single();
TrBineId is my viewModel,any way the number of controllers are increasing and also in each controller i have many different LINQ,should i start with generic repository?
The damn reason to use repository pattern lies in implementing your solution with a clear separation of concerns and leverage domain I/O in a way that can be reused across your codebase.
You should start to revisit OOP and you'll need to double-check repository pattern.
At the end of the day, the need for certain patterns is already there, but it'll arise in your mind once you put the pieces in order.
I would start following some tutorial around the net about repository pattern to implement a proof-of-concept project and realize how it works.
Finally, Inversion of Control and Dependency Injection are concepts you'll need to manage to integrate your repositories and other patterns in your project to increase code composability and testability.
DISCLAMER: The following links are from my website about software architecture. You might want to check them as a possible reference implementation of repository pattern:
Repository
Agnostic repository
The repository pattern allows you to use the concept of Single responsibility principle, which mean (as an overview) one class = one role.
Your controler class is here for managing the request (Get, Post) and send back a response (FileResult, ActionResult...).
For the Data access (DAL, DAO) you will usually create a class per model entity (ClientRepository, CommandRepository), and you will create your methods for getting them (GetClients(), GetOneClientById(int id)...) within this class.
Edit for clarification after Matías comment:
This class will be called in your controller through his interface that you will also implement (with IOC or not).
You will then create a class instance of ClientRepository in your controller, but assigned to a reference of the interface type (IClientRepository).
**End Edit **
So we can imagin for Client Entity:
ClientController(All route for clients data)
IClientRepository (interface)
ClientRepository (Class which implement IClientRepository )
Then, in your controller you will call the repository like
IClientRepository clientRepo = new ClientRepository();
And then use the methods:
ICollection<Client> clients = clientRepo.YourMethod(int param1);
Advantages:
First of all, your code will be more clear and maintainable. Your DAO (DAL in .net) will keep the data access layer and you could use the GetAllClients method many time and you will not repeat yourself (DRY).
You can also apply easily some param on the method (like order, limit for pagination etc...)
It will be testable as well, I don't think that calling database in the controller can give you reasonable unit test results. You will also catch excption with a more "elegant way".
Small tip : When you will have more experience in the repo pattern, you could have a look at the Inversion of Control pattern

Where to put the method. Service layer ( BL ) over repository?

I'm confused about one thing. I've used a repository pattern (not generic) in my previous mvc apps and I used to include some kind of business logic there. At this moment I read about service layer pattern where should be included BL. But now I don't know if there is more abstraction and extra code instead of cleary/readable and efficient code.
I want to implement a method like this
public void ChangeActiveField(bool isActive, int id)
{
var objectToUpdate = _context.FirstOrDefault(x=>x.id==id);
objectToUpdate.IsActive - isActive;
_context.Entry(objectToUpdate).State = System.Data.Entity.EntityState.Modified;
_context.Save();
}
In this code there is a bit of business logic where I change state of one field and after that I update this.
Should I make it in service layer and then use simple repository update method liek this: ?
public class MyService
{
private readonly IMyRepository = _myRepo;
MyService(IMyRepository myRepo) //it's injectable
{
_myRepo = myRepo;
}
public void ChangeActiveField(bool isActive, int id)
{
var myObject = _myRepo.GetMyObject(id);
myObject.IsActive = isActive;
_myRepo.Update(myObject);
}
}
Is it better aproach? Does it make better separation? Or it's too sophisticated and overwrite?
Thank you for your help.
Best regards.
In general repository should encapsulate only the logic of accessing database (initialization of context, transactions, connections and etc.). It is very common to create a generic CRUD repository and reuse it for all your business entities.
All the business related logic should be placed in business layer(service layer).
The major benefits of this approach are:
Testability - you can test your business logic without relying on concrete repository implementation by injecting fake repositories(stubs).
Decoupling - neither your business layer nor your UI are not coupled to specific database, If tomorrow you will decide to migrate your database for example from SQL server to Redis(NoSQL database), your changes will be contained on repository layer only.
Maintainability - there is a clear separation of concerns for each layer: UI - interaction with user, BL - implementation of business logic, Repository - interaction with DB.
In my experience having a business layer (no matter how simple it is at the beginning - it's often grows up together with your project) is always a good idea.
By the way some developers consider repository as an unnecessary layer of abstraction in case that you use EF (in a way EF database context is a repository...).
One thing I've learned, is that the major effort is not a development phase of a project it is it's maintenance and upgrades - and here having a business layer a significant impact.
Disclaimer: It is my subjective opinion based on my experience

Unit of Work through tiers

I'm refactoring an existing MVC.Net application to include the unit of work pattern to make data management a bit more obvious and straight forward.
The application is currently split into
Presentation/UI (MVC Controllers delivering views OR JsonResults for AngularJS)
Business Logic (Containing well... business logic)
DAL (Repositories and EF)
I'm having a hard time trying to figure out how I need to be structuring dependency injection and UoW passing to keep things sensible and testable.
I'm anticipating something like the following to be an example:
public class SomeMVCController : Controller
{
private readonly IStoreFrontLogic _storeFrontLogic;
public SomeMVCController(IStoreFrontLogic storeFrontLogic)
{
_storeFrontLogic = storeFrontLogic;
var uow = new UnitOfWork(User);
_storeFrontLogic.UnitOfWork = uow;
}
public ActionResult SomeRequest()
{
var myViewModel = _storeFrontLogic.OffersForUser();
return View(myViewModel);
}
}
public class StoreFrontLogic : IStoreFrontLogic
{
public UnitOfWork unitOfWork;
public OffersModel OffersForUser()
{
//some logic taking into account the current user in the uow
var prevOrders = unitOfWork.OrdersRepo.GetUsersOrders();
// special offers logic
return specialOffers;
}
}
Does this seem sensible?
I'm not too keen on the requirement to manually push the uow into my logic classes whenever they're required. Is there a more sensible way?
As I said above, this is hard to answer without a specific question or specific domain model but I'll give it a shot.
My understanding of such things is focused pretty heavily through a Domain Driven Design lens.
First of, you should read this series of papers on effective aggregate design. The fact that you need units of work and to do queries from inside your domain classes implies that your model needs work.
Some other thoughts on UOW - having uow produce your repositories is good, but I think you will likely start hitting lots of difficulties with implementation. UoW is super useful in small targeted areas but is very difficult to implement across an entire application. What for example happens when you save? Can you never use EF directly? Is everything thread safe? You might want to simplify what you are trying to achieve.
In your example uow can be scoped to the HttpRequest. Many IoC containers (eg Structuremap) provide a simple way to configure this. You can then have a post-action filter (or even better an OWIN module) to attempt the commit (what happens if there are errors is yet another implementation difficulty to deal with). This will eliminate a lot of the property-assignment nonsense
I'm not sure what type of object is your StoreFrontLogic. It doesn't seem like a domain entity but it contains significant business logic. It could be something similar to a transaction script, but in that case the uow should be fully internal to it.
Is it a stateless service? In that case everything that method uses - orders for user included - should be passed in via a parameter.
If, on the other hand it's an entity then it shouldn't access the database at all, it should already have all orders for the user. Purposeful database denormalization can help quite a bit here.
At the very least pass uow as a parameter to OffersForUser rather than expecting for a property to be set.

EF - 3 tier not safe

Supposing a classic 3 tier application. In DAL, you have a GenericRepository where T represent your POCO class and it include some method like Insert(T entity), Delete(T entity), Update(T entity) and so on. Then, your BLL (business logic class) contains something like CustomerRepositor.
Well, all rights.
Now, image your aspx page:
var customers = BLL.CustomerRepository.GetAll();
customers.First().Name = "some name";
Not good, you have to pass by CustomerRepository.Update, Insert or Delete methods in order to I can execute some validation for all CRUD operations. In this way all business logic will not works as I aspected.
I note that no-one has never thought about this, but I think is an important question. has not make sense to have business method for CRUD operation if yuo can bypass them.
Am I missing something?
Well, lets start.
var customers = BLL.CustomerRepository.GetAll();
This was a nice line of code in the last millenium. Before generics and LINQ came along. Seirously.
These days, I would expect it at least to be like this:
var customers = BLL.Repository<Customer>.ToList (); //IF you have to materialize
There is no need for an "All" method at all ;)
Am I missing something?
To a large degree an understanding that you are still within an application, so compromises are sort of acceptable. It is not like you run a trust boundary between applications here. Second, the fact that you should have programmed a better abstraction.
Repository repository = BLL.GetRepository ();
var customer s repository.Entity<Customer>.ToList ();
customer[0].Name = null;
repository.ValidateU ();
repository.Commit ();
would be a lot better abstraction. Creation is not done with "new" but with
var newCustomer = repository.Create<Customer> ();
which then commits.
All validation can be checked in the Validate method.
At the end, this is about HOW you design your interface for the repository - and if you insist on not keeping any state (which is a valid pattern for some operations) then this opens you to problems. And yes, you can have repositories that do not do full validation - totally valid. It really depends. You may be surprised, but I work on applications mostly where the repository is often not even updated in the same transaction as the object for performance reasons, and updates are queued and then batched, while the in memory version is the relevant one for all further operations.
It shows, at the end, that a little more thinking about how to design the DAL interface is in order, and please please please stop using an approach that is totally outdated and just leads to method creep (as you need tons of methods that otherwise just disappear in generics + linq expression trees.

Save Me on a Business Object

I've commonly seen examples like this on business objects:
public void Save()
{
if(this.id > 0)
{
ThingyRepository.UpdateThingy(this);
}
else
{
int id = 0;
ThingyRepository.AddThingy(this, out id);
this.id = id;
}
}
So why here, on the business object? This seems like contextual or data related more so than business logic.
For example, a consumer of this object might go through something like this...
...Get form values from a web app...
Thingy thingy = Thingy.CreateNew(Form["name"].Value, Form["gadget"].Value, Form["process"].Value);
thingy.Save();
Or, something like this for an update...
... Get form values from a web app...
Thingy thingy = Thingy.GetThingyByID(Int32.Parse(Form["id"].Value));
Thingy.Name = Form["name"].Value;
Thingy.Save();
So why is this? Why not contain actual business logic such as calculations, business specific rules, etc., and avoid retrieval/persistence?
Using this approach, the code might look like this:
... Get form values from a web app...
Thingy thingy = Thingy.CreateNew(Form["name"].Value, Form["gadget"].Value, Form["process"].Value);
ThingyRepository.AddThingy(ref thingy, out id);
Or, something like this for an update...
... get form values from a web app ...
Thingy thingy = ThingyRepository.GetThingyByID(Int32.Parse(Form["id"].Value));
thingy.Name = Form["Name"].Value;
ThingyRepository.UpdateThingy(ref thingy);
In both of these examples, the consumer, who knows best what is being done to the object, calls the repository and either requests an ADD or an UPDATE. The object remains DUMB in that context, but still provides it's core business logic as pertains to itself, not how it is retrieved or persisted.
In short, I am not seeing the benefit of consolidating the GET and SAVE methods within the business object itself.
Should I just stop complaining and conform, or am I missing something?
This leads into the Active Record pattern (see P of EAA p. 160).
Personally I am not a fan. Tightly coupling business objects and persistence mechanisms so that changing the persistence mechanism requires a change in the business object? Mixing data layer with domain layer? Violating the single responsibility principle? If my business object is Account then I have the instance method Account.Save but to find an account I have the static method Account.Find? Yucky.
That said, it has its uses. For small projects with objects that directly conform to the database schema and have simple domain logic and aren't concerned with ease of testing, refactoring, dependency injection, open/closed, separation of concerns, etc., it can be a fine choice.
Your domain objects should have no reference to persistance concerns.
Create a repository interface in the domain that will represent a persistance service, and implement it outside the domain (you can implement it in a separate assembly).
This way your aggregate root doesn't need to reference the repository (since it's an aggregate root, it should already have everyting it needs), and it will be free of any dependency or persistance concern. Hence easier to test, and domain focused.
While I have no understanding of DDD, it makes sense to have 1 method (which will do UPSERT. Insert if record doesn't exist, Update otherwise).
User of the class can act dumb and call Save on an existing record and Update on a new record.
Having one point of action is much clearer.
EDIT: The decision of whether to do an INSERT or UPDATE is better left to the repository. User can call Repository.Save(....), which can result in a new record (if record is not already in DB) or an update.
If you don't like their approach make your own. Personally Save() instance methods on business objects smell really good to me. One less class name I need to remember. However, I don't have a problem with a factory save but I don't see why it would be so difficult to have both. IE
class myObject
{
public Save()
{
myObjFactory.Save(this);
}
}
...
class myObjectFactory
{
public void Save(myObject obj)
{
// Upsert myObject
}
}

Categories

Resources