Datasource, Repository, ViewModels and IoC Container. Is a Repository really needed? - mvvm

I current got a flow like this:
The Repository gets injected with a Datasource. The ViewModel gets injected with the Repository.
Because there's a constant flow of Items and Mutations (deletions, changes) that need to translate to the UI I don't keep a collection of items in the Repository. Therefor I ended up with a repository that only passes along Items between the Datasource and the ViewModels.
I've always understood that you shouldn't directly use the Datasource in the UI layer (ViewModels are in my UI layer). But is this still the case if you use dependency injection? Am I putting the Repository pattern to its use or is it just causing me overhead? (Right now it feels like it does.)
I originally implemented the repository to decouple the UI and Datasource but I've found that DI does a great job without a Repository.

You might want to have a look at some of the blog posts by Oren Eini (aka Ayende Rahien)
The evils of the repository abstraction layer
or
Repository is the new singleton
More often than not repositories are just "flow heaters". They do nothing but forward calls and results and just add overhead.
Btw: if you should or should not use repositories has nothing to do with dependency injection!
Update
Oren just published a new post on this topic.

Related

Why do we inject database context in repositories instead of creating database context inside repository class itself?

One of the objectives of Repository pattern is supposed to decouple business logic with data access. Then why is it that database context is not created in repository class itself instead of being provided to it by service layer or controller?
You pass the context in because you may have a transaction that spans repositories. The context is the unit of work for the repositories.
Database Context represents your Unit Of Work in most cases. With this in mind, there are at least two reasons to inject it in repositories instead of creating it in repositories.
Using same Context across multiple repositories
Many articles say Transaction is responsibility of Repository. But, in practical world, this may not be the case every time. One may need to span the transaction across multiple repositories. To achieve this, there is no better way than to inject it.
Manage Context at some higher level (Context per Request in Web may be) which is not accessible to Repository
This is not much different than above. Many implementations manage Context at higher level which is not accessible to Repositories. Context per Request is popular example. In this case, Context must be separated somehow from Repositories and handled differently. But, repositories does need the Context; so just inject it.
Contexts exposed by full ORMs implement change tracking at good scale. To take better advantage of this feature, it is better if Context is separated from Repositories.
Imagine the case where your repository call is successful but you do not want to flush because your other file action failed.
By separating Context from Repository, you better implement SRP. Context handles responsibility of Change Tracking and Flushing. Repository hold in-memory representation of data with changes if any and allows to read/write this in-memory data.

Encapsulating an external data source in a repository pattern

I am creating the high level design for a new service. The complexity of the service warrants using DDD (I think). So I did the conventional thing and created domain services, aggregates, repositories, etc. My repositories encapsulate the data source. So a query can look for an object in the cache, failing that look in the db, failing that make a REST call to an external service to fetch the required information. This is fairly standard. Now the argument put forward by my colleagues is that abstracting the data source this way is dangerous because the developer using the repository will not be aware of the time required to execute the api and consequently not be able to calculate the execution time for any apis he writes above it. May be he would want to set up his component's behaviour differently if he knew that his call would result in a REST call. They are suggesting I move the REST call outside of the repository and maybe even the caching strategy along with it. I can see their point but the whole idea behind the repository pattern is precisely to hide this kind of information and not have each component deal with caching strategies and data access. My question is, is there a pattern or model which addresses this concern?
They are suggesting I move the REST call outside of the repository
Then you won't have a repository. The repository means we don't know persistence details, not that we don't know there is persistence. Every time we're using a repository, regardless of its implementation (from a in memory list to a REST call) we expect 'slowness' because it's common knowledge that persistence usually is the bottleneck.
Someone who will use a certain repository implementation (like REST based) will know it will deal with latency and transient errors. A service having just a IRepository dependency still knows it deals with persistence.
About caching strategies, you can have some service level (more generic) caching and repository level (persistence specific) caching. These probably should be implementation details.
Now the argument put forward by my colleagues is that abstracting the data source this way is dangerous because the developer using the repository will not be aware of the time required to execute the api and consequently not be able to calculate the execution time for any apis he writes above it. May be he would want to set up his component's behaviour differently if he knew that his call would result in a REST call.
This is wasting time trying to complicate your life. The whole point of an abstraction is to hide the dirty details. What they suggest is basically: let's make the user aware of some implementation detail, so that the user can couple its code to that.
The point is, a developer should be aware of the api they're using. If a component is using an external service (db, web service), this should be known. Once you know there's data to be fetched, you know you'll have to wait for it.
If you go the DDD route then you have bounded contexts (BC). Making a model dependent on another BC is a very bad idea . Each BC should publish domain events and each interested BC should subscribe and keep their very own model based on those events. This means the queries will be 'local' but you'll still be hitting a db.
Repository pattern aim to reduce the coupling with persistence layer. In my opinion I wouldn't risk to make a repository so full of responsibility.
You could use an Anti Corruption Layer against changes in external service and a Proxy to hide the caching related issues.
Then in the application layer I will code the fallback strategy.
I think it all depends where you think the fetching/fallback strategy belongs, in the Service layer or in the Infrastructure layer (latter sounds more legit to me).
It could also be a mix of the two -- the Service is passed an ordered series of Repositories to use one after the other in case of failure. Construction of the series of Repos could be placed in the Infrastructure layer or somewhere else. Fallback logic in one place, fallback configuration in another.
As a side note, asynchrony seems like a good way to signal the users that something is potentially slow and would be blocking if you waited for it. Better than hiding everything behind a vanilla, inconspicuous Repository name and better than adding some big threatening "this could be slow" prefix to your type, IMO.

Using Repository Pattern With Entity Framework 6

Is it a best practice to implement repository pattern with entity framework 6 (and upper versions)? why? It seems that Microsoft doesn't recommend it!
I think it is a good idea to add repository pattern over entity-framework as it can help you alot in many areas. But it can also add a new layer of complexity. So points to consider are:
Using repository you can limit clients to specific operations. (Can be a pro or con depending on requirements and implementation)
You can also provide ready made functions for complex operations so client don't have to repeats that logic.
Repositories can be made thread safe as DbContext isn't.
Repositories will allow you to be independent of entity framework so in future if you ever need to move away from it you can just changed underlying functionality easily.
You can intercept incoming db operations in repository and do whatever you like with them. e.g. add addition where clause in multi-company scenario.
Testing becomes more easier as it becomes easy to mock underlying functionality.
But Repositories also have others cons.
Look at these Is the Repository pattern useful with Entity Framework?
and Benefit of Unit of Work and Repository Pattern with Entity Framework

Repository and IoC Patterns

Previously I asked this question and on a answer I got this comment:
This works, however injecting the container to a part, as far as I know, is not a "normal" use-case of MEF.
In my web app I have a few repositories that, of course, retrieve entities from the DB. To make them as loosely coupled as possible I'm making them return interfaces (eg IUser, IBill, IBlaBlaBla...) and the repository project only references the library project (that contains the interfaces). I use MEF composition capabilities to tie it all up...
Since the repository must have a concrete object to fill with info it got from the DB and the only the Container is aware of which concrete class maps to a specific interface I think that the repository MUST have reference to the container so it can call the "Resolve()", get a new instance and do his job, but that apparently is a mistake.
Can anyone tell me why and what approach would be better?
PS: I don't know if it's relevant but I'm using DDD...
I think the flaw in your design that lead to this problem is the use of interfaces to hide entities behind. Since entities are your core concept in your domain, there should be no use in hiding them behind an abstraction. Let's put it differently: do you ever have a different implementation of IUser?
In other words, ditch the IUser, IBill, etc. interface and let your repositories and business commands depend directly on your aggregate entities.

Entity Framework generic repository life cycle

I've read a couple of articles about creating a generic repository in Entity Framework. In every article the ObjectContext is passed as an argument to the constructor like this:
public Repository(ObjectContext context)
{
_context = context;
}
In a web application the preferred way to handle ObjectContext lifestyle is per web request. This means that these repositories must also have lifestyle per web request, if used in in a web context. This spreads to services using repositories and further on if we stick to constructor injection...
I think the ObjectContext life cycle should be handled outside the repositories, for example in a HttpModule. I would also like to handle repositories as singletons instead, and then ObjectContext can't be injected in the constructor. Another mechanism for getting the ObjectContext into the repository must be used, like an ObjectContextFactory.
Whats the downside of handling the repositories with a singleton lifestyle?
One issue with repositories being singletons, as with any other objects, is that determining what dependencies the repository has becomes more difficult. When you require that a context is passed in the constructor that is a clear declaration of a dependency on the ObjectContext class. If you were to use a static factory to get a reference to an object context then it would be necessary to see the implementation of the repository to know how it uses the factory.
A common way to achieve what you're looking for, namely the ability to manage the scope of the ObjectContext class outside of the repository is by using a dependency injection library, such as Autofac. You can register the ObjectContext class such that a new instance is created for every HTTP request. Then if you also register the repository class, when a repository is requested the dependency injection container will attempt to get a reference to the ObjectContext dependency. Since only one instance of ObjectContext will be created per HTTP request multiple repositories within that scope will receive the same instance. The Autofac page has example of integrating with ASP.NET that you can look at.