Redesign repository in MVVM application to increase testability - c#

I've inherited a WPF MVVM application which has virtually no unit tests. When I tried to write my own, I quickly realised why: the code hasn't been written in a manner that makes it easy to test, with a lot of concrete implementations.
A particular bugbear is the repository. There's an EF context underneath which I can't/don't want to test but I'm struggling to even get the thing to accept Mocks of the EF objects instead.
I'll hold my hand up and say: I'm not a very good architect. Can you help me untangle this a bit, and prod me toward where interfaces and such need to be added?
Here's a sample ViewModel from the application:
public class MyViewModel : BaseViewModel
{
public MyViewModel(MyEFObject mEfObj)
{
//do stuff
}
// properties, methods etc etc
}
They all inherit from BaseViewModel:
public abstract class BaseViewModel : INotifyPropertyChanged
{
private static MyRepository _rep;
protected static MyRepository rep
{
get
{
if (_rep == null)
_rep = new MyRepository();
return _rep;
}
}
// properties, methods etc etc
}
And so to the repository class:
public class MyRepository
{
private MyEntitiesT db = new MyEntitiesT();
//methods and properties that interact with the DB
}
And finally, at the bottom of the heap, that slightly peculiar entity wrapper:
public class MyEntitiesT : MyEntities
{
public MyEntitiesT()
{
var objectContext = (this as IObjectContextAdapter).ObjectContext;
objectContext.CommandTimeout = 0;
}
}
So, I guess I really need an IMyRepositoryInterface over MyRepository, which would allow me to Mock that. But if I'm instantiating a MyViewModel object, how do I get in my mocked repository, since it's specified in BaseViewModel? Do I need to start fiddling with dependency injection?
Poor testability aside, this is a pretty functional application that I don't want to mess with excessively for fear of breaking it. So if there's a way I can get these things decoupled without making major structural changes, or at least by making them piecemeal (i.e. one ViewModel at a atime) it'd be useful.

You are right. You need IRepository and an implementation containing all the EF code like EfRepository.
I also saw that you are passing and EF Object to a ViewModel...
MyEFObject mEfObj
usually you just want to retrieve POCO's from your Repositories and pass in the Repository to the view model.
So start piece by piece. Take your existing repository and define an interface for it and implement it in the repository. And start to exchange the concrete class definition in the constructor with the interface... and then work from there how deep you need and want to go...
And start adding tests on your way... they will build up soon...
Before you use Dependency injection framework start with something like this...
private readonly IRepository _repository;
public MyViewModel() : this(new EfRepository())
{
}
public MyViewModel(IRepository repository)
{
_repository = repository;
}
This should only be an intermediate step but helps you to refactor to implement a contract based on interfaces. After that look for DI and ViewModelLocator pattern
To go with constructor injection and Interfaces is a good step because they are easy mockable and you can also use mocking frameworks to provide expected behavior from within your unit test.
HTH

Related

Decoupling EF6 from its custom Api

I would like to ask some help regarding Dependency Injection and, I think, architectural approach.
So, I have an ORM layer implemented by EF6 where the objects are described and Ef does what its business, etc. I created a custom library over it, called DatabaseApi and it is mentioned in the title as "Api", where I query the data and map it to datacontract objects. I do it for pure testing purposes. I would like to have the different libraries in my application testable.
I started to implement the code where I inject the DbContext but I don't know how to deal with the usings in this case.
I went through a few blogposts and articles about mocking and EF, especially this one but it is rather about testing EF itself and not about how to decouple it from other libraries. On the other hand, I assume my search keywords were not proper.
Do you know any good and usable tutorials and articles about how to decouple entity framework from other libraries?
Thanks in advance!
Examples:
I created an empty interface in order to the DbContext can be injectable. It is implemented by the databaseContext.
public interface IDatabase
{
}
public class DatabaseModelContext : DbContext, IDatabase{
public DbSet<TableOne> TableOne { get; set; }
public DbSet<TableTwo> TableTwo { get; set; }
}
In the custom Api library constructor I put together a code to resolve the interface by Unity. I don't know whether it is working or not. I haven't executed yet.
public partial class DatabaseApi : IDatabaseApi {
private readonly IDatabase iDatabase;
private readonly UnityContainer unityContainer;
public DatabaseApi()
{
this.unityContainer = new UnityContainer();
this.unityContainer.RegisterType<IDatabase, DatabaseModelContext>();
this.iDiLibDatabase = this.unityContainer.Resolve<IDiLibDatabase>();
}
}
And here is the problem. Due to the injection I'll have and interface but there are the usings which are important to manage the resource as far as I know. How to do it?
public partial class DatabaseApi : IDatabaseApi
{
public List<SomeDataContract> GetMainStructure()
{
var result = new List<SomeDataContract>();
//this is the old implementation
using (var database = new DatabaseModelContext())
{
//some data manipulation magic... :)
}
return result;
}
If you're okay using linq to objects as a core element of your domain access layer then exposing an IQueryable for access to the entities would work...
public interface IRepository<TEntity>
{
IQueryable<TEntity> AllEntities { get; }
}
With that, you can do your Where, Select, etc. without hard wiring directly to EF. Behind the scenes the IRepository implementations would deal with the EF portions, database connectivity, etc. There's no avoiding coupling the to EF at the data access layer. But you can keep it constrained to just that layer using something like you've started. Just make sure the database contexts used by your IRepository objects are the only objects working with EF.
Put another way: Don't have your IDatabase return entities. Just have it deal with the connections, and you should create another layer for domain object access which takes in an IDatabase. In the example I gave, somehow the IRepository implementations would take in an instance of IDatabase.
So, the solution is using Autofac DI framework. I found interesting questions and answers and two really helpful tutorials. Links below:
How do you reconcile IDisposable and IoC?
Dependency Injection with Autofac
Generic Repository and Unit of Work Pattern, Entity Framework, Unit Testing, Autofac IoC Container and ASP.NET MVC
Autofac homepage

Correct use of Repository and Unit Of Work patterns in ASP.NET MVC

I have been trying to implement a generic repository in MVC with Unit of Work and Dependency Injection with Ninject.
The post I have been following is this one
http://codefizzle.wordpress.com/author/darkey69/
I am not getting anything returned when I try to use the repository in my controllers. I suspect it is because there is nothing that specifically links or injects the EFDbContext and cannot seem to work out how to do this.
If anyone has implemented this and can assist that would be greatly appreciated. I won't re-post my code just yet as it is all contained and explained in the post above.
While, ultimately, I would discourage you from using the UoW/Repository patterns with an ORM like Entity Framework, I can still give you an approach I've toyed with, which may be helpful even in something more appropriate to abstracting your context, like a service.
All the link you posted is doing is using generics so you don't have to actually define separate implementations of IRepository for each particular entity type. However, you still must manually new up an instance of the generic repository for each entity type in your IUnitOfWork implementation and alter the interface itself to include each entity's repository instance if you want to actually be able to work with the interface instead of the actual generic instance. Not only is that cumbersome, but it also violates open-closed on both UnitOfWork<T> and IUnitOfWork, and keeping them in sync with changes is going to be loads of fun, as well (read: sarcasm).
An alternative I've toyed with, though I won't go so far as to recommend it, is to use generic methods instead of generic classes. For example, instead of something like:
public class Repository<T> : IRepository<T>
where T : class
{
...
public IEnumerable<T> GetAll()
{
return _dbSet;
}
}
You might do:
public class Repository : IRepository
{
...
public IEnumerable<T> GetAll<T>()
where T : class
{
return context.Set<T>();
}
}
Which means, you only need to new up one Repository instance, and you can then access any entity type in your context off that:
var repo = new Repository(context);
var foos = repo.GetAll<Foo>();
var bars = repo.GetAll<Bar>();
This, of course, negates the need entirely for a unit of work.
The reason I won't necessarily recommend this approach is that it hasn't been field tested. As I've said, I've toyed around with it personally a bit, and I feel comfortable with it myself. However, I'd very much be interested to hear what other developers think of this approach.

PHP and C#.NET MVC ( repository pattern in PHP, how might i go about it )

I love the Unity and Ninject framework with dependency injection for C#.NET into the controllers with repository interfaces etc, but I am trying to think up an alternative in PHP and am struggling.
I have:
class User
{
//..
}
interface IUserRepository
{
public function Repository(); // This can't work as a variable, should I abstract?
}
class UserRepository implements IUserRepository
{
public function Repository()
{
$users = // DAO gets users and returns them..
// But how does the IUserRepository help me at all? Even if I had ninject or
// Unity creating some new link between the UserRepo and IUserRepo?
return $users;
}
public function GetAllUsers()
{
// errr.. I'm confused
}
}
// Something has to say if the AdminController is called,
// inject into its construct, a new IUserRepository
class AdminController extends Controller
{
private $repository;
public function __Construct( $repository )
{
$this->repository = $repository;
}
public function ActionResult_ListUsers()
{
$users = $repository->GetAllUsers();
// Do some clever View method thing with $users as the model
}
}
The real question is PHP and repository approach. How does that work? You can see I'm blotching this a bit and really want to get it right!
EDIT::
Even more simple question. What is the benefit of the interface keyword? How does declaring an interface with some methods undefined and then making a new class that implements those methods to extend them, help when you cannot create a new interface like a class that then is filled in with the proper class that defines them?
Kind of a broad question but I'll take a shot. Symfony 2 is a modern php framework built around an excellent dependency injection container. Symfony 2 supports Doctrine 2 which is a modern orm persistence layer in which repositories are supported.
Skim through here: http://symfony.com/doc/current/book/doctrine.html
Skip all the details on setting things up and instead look for:
Creating an Entity Class
Persisting Objects to the Database
Fetching Objects from the Database
The fetching section is where repositories come into play. This gives you a broad overview of one way to implement repositories on php. You might decide to research more on Symfony 2/Doctrine 2 or you may go another route entirely. But this will give you a starting point.
As far as interfaces go, I hate to say it but that is a real real real basic question. Might want to go through some OOP tutorials? A one or two sentence explanation is probably not going to make much sense.
====================================================
This may help a bit:
class User
{
//..
}
interface IUserRepository
{
public function getAllUsers();
}
class UserRepository extends DoctrineRepository implements IUserRepository
{
public function getAllUsers()
{
return $this->findAll();
}
}
class AdminController extends Controller
{
private $repository;
public function __Construct(IUserRepository $repository )
{
$this->repository = $repository;
}
public function ActionResult_ListUsers()
{
$users = $this->repository->getAllUsers();
// Do some clever View method thing with $users as the model
}
Your User and IUserRepository would reside in what is known as a domain layer.
The actual UserRepository implementation would be in a service layer. You might have multiple implementations. One talking to a sql database. Perhaps another talking to MongoDB or maybe just a file.
You controller lives in yet another layer. It expects to receive an object the implements an IUserRepository and thus has a getAllUsers method. Your controller does not care how the repository is actually implemented. All it knows is what is exposed via the interface.
It's up to your application to wire things up using dependency injection such that the controller gets the correct repository.

Confusion over IRepository

I'm a bit confused about when using the "IRepository pattern", when actually to load the data.
Currently I have something like this:
public class MainViewModel : ViewModelBase
{
// EF4 generated ObjectContext
private ScorBotEntities context = new ScorBotEntities();
// Custom IUserRepository class
private IUserRepository userRepository;
public MainViewModel()
{
this.userRepository = new UserRepository(context.Users);
}
public ObservableCollection<User> Users
{
get
{
return new ObservableCollection<User>(userRepository.GetAll());
}
}
}
ScorBotEntities are autogenerated using EF4 (I had a look at POCOs, to much work for this sized project).
You can find the definition of the UserRepository here: http://code.google.com/p/i4prj4-g2/source/browse/ScorBotRobotics/ScorBotRobotics/Repositories/UserRepository.cs
But basically, what I'm wondering about is, why do it even make sense to use a repository here, instead of just writing it like this:
public class MainViewModel : ViewModelBase
{
private ScorBotEntities context = new ScorBotEntities();
public MainViewModel()
{
}
public ObservableCollection<User> Users
{
get
{
return new ObservableCollection<User>(context.Users);
}
}
}
It makes sense to abstract functionality away such as with the UsernameAndPassword method. But in that case, perhaps using some Query Objects would be more ideal?
I am a bit baffled that your context has made its way down to your ViewModel. I believe your GUI layer should never see the context. Context must be opened/kept/closed by the IRepository. Let the data layer (IRepository) return an array/list of Users.
There are a couple of different points here. First, your view models should have no knowledge of the repository - keep your view models as simple as possible.
Second, the IRepository is your public API - so you should have dependencies to this (depend on abstractions rather than concrete implementation between layers).
There are a couple of different (perfectly acceptable ways) to implement the IRepository. One is to have the repository encapsulate the context directly. Another is to use the "unit of work" pattern and have your unitOfWork encapsulate the context and pass the unitOfWork object to each repository. Either way, since you're using EF4, testability is much easier than it used to be. For example, EF4 introduced IObjectSet so that it is easy to provide test doubles and mocks to test your repository.
I highly recommend checking out this whitepaper on Testability and Entity Framework 4.
Separation of concerns
What if you want to change the storage of 'Users', from say SQL to a flat file?
Then context would not be needed, and you'd have to change every use of it, instead of just your IRepository implementation.
Also, ideally you would have your IRepository injected. So you're MainViewModel doesn't care how it gets it's Users.

Decorator Chaining of Repositories and Specialized Repositories with Dependancy Injection

Right now I'm trying to figure out a way to do things smarter, and in the course of doing so all i've managed to do is use a full bottle of excedrin in a single day.
Assume i have an interface called IRepository like so.
public interface IRepository<T>
{
T Get(int id);
void Add(T value);
void Update(T value);
void Delete(T value);
...
}
And assume i have an implementation like
public class NHibernateRepository<T>
{
...
}
Now, all is fine and good, i can do all my basic operations against the repository to support all CRUD functionality, but i may want specialized operations, so assume i have an interface like this:
public interface IUserRepository : IRepository<User>
{
IList<User> GetUsersByRole(Role role);
}
And an implementation like such:
public class UserRepository : NHibernateRepository<User>, IUserRepository
{
....
}
Ok, so that is the basic setup, now there's one more thing that i want to do. I want to have logging and transaction and things like that all transparently. So what i would like to do is use a dependency injection framework like Castle Windsor or StructureMap so that when i ask for IRepository, i'll get it wrapped by a LoggingRepository and a TransactionRepository, both of which implement IRepository.
So, what i want to do is something like this:
IUserRepository repository = container.Resolve< IUserRepository>();
and have it return a user repository that's wrapped in the Logging and Transaction decorators, but i can't think of a way that this will ever work. The only way i can think of getting this to work is by implementing UserRepository like such:
public class UserRepository : DecoratorRepository<T>, IUserRepository
{
protected IRepository<T> Repository { get; set; }
public UserRepository(IRepository<T> innerRepository)
{
Repository = innerRepository;
}
}
This would mean that we would use Dependancy Injection to create a decorated repository and pass that into the constructor of the UserRepository and then use that as the repository in which we run operations against. This would work, but i still don't think it's ideal.
So, my question is, am I right in that this is the only way to do this, or am I not understanding this correctly or just missing something all together. Also, if you have run up against this problem before, how did you solve this problem?
If you are going to use decorators that sounds about right. Each decorator would have a constructor with an argument of IRepository and call the logging or transaction code around calls to the inner repository that it is decorating.
As an alternative you might consider, but that I have very little experience with is Aspect Oriented Programming. In that scenario you apply attributes to your classes that indicate what logging or transaction methods you want to use. At some point those methods get weaved into your code, this can be done as either as an extra compile step, or in the case of the SpringFramework.net at time of injection.
Couldn't you have a LoggingRepository abstract base class that would handle logging for your different Get, Add, Update, Delete, make them virtual and then inherit from them?
I'm not sure though what problem you are trying to solve though as I would think you may have tried this? You could wrap in transactions as well, though most likely you'd want to do that in your NHibernateRepository.

Categories

Resources