Is there something to do Dependency Injection with model classes? - c#

I'm developing software (libraries, Web pages, Web API, desktop applications, etc.) using C#, .NET Framework 4.0 and Entity Framework Code First.
To develop this software I'm using Dependency Injection with Ninject, and patterns Generic Repository and Unit of Work.
This is the first time I use those patterns and I thought that using Ninject I will solve the problem of coupling.
Now, I have improved my database and I have changed model. The database has the same functionality that the previous one but with less tables and less columns. To do that I have changed my E.F.'s POCO classes and here comes all of my problems. These problems come because I'm using these POCO classes inside my business logic and if I change them I have to change business logic.
I thought that using Dependency Injection I will isolate data layer from business layer, but it doesn't. If changing my data layer I have to change business layer I'm coupling both.
This always happens or have I done something wrong?

Dependency injection allows you to substitute in alternative implementations of a contract, usually via an interface. That contract is made up of types and methods, so if either changes you have a new contract. Your POCOs are part of this so out have to expect changing them will generate rework.
If you separate out model classes outside of entity framework and use them you'll get better separation but more type casts.

Related

Is Entity Framework a repository

In the sense of application layers, I have a hard time figuring out, how to place Entity Frameworks DbContext. It seems to me that it aims to replace the repository layer, but on the other hand it doesn't really work like a more basic repository, which is implemented via an interface, making it easy to swap later.
So I found a lot of good posts on the service and repository layer (e.g. this post), but it doesn't seem to answer where Entity Framework fits in this pattern.
Should I add a repository layer on top of Entity Framework or should I just use DbContext in place of a repository, in my services?
You need to ask yourself why would you want to abstract away your data-access layer.
The answer would typically be:
Unit Testing
Replacing the layer with another DB / persistence technology
Many are arguing that the 2nd argument is utterly false because:
Replacing that layer would usually have a much wider effect on your application than just configuring another implementation
It rarely happens and doesn't worth the effort
All in all, I tend to agree that testability should be your main concern and in the case of EntityFramework you can:
Use EF Core with its built-in InMemory provider
Use EF 6 and mock all the methods and DbSets in your context (by marking them as virtual).
And, to answer your question title: Yes. DbContext is already acting as a repository.
EF isn't a layer, it's a data access technology.
EF calls should be written inside a repository, which serves as an abstraction to the service layer so that the service layer doesn't care if the data are stored in a database or somewhere else.

n Layered Asp.net app with Entity framework

I am facing the same issue as the one below
Entity Framework 6 and Unit Of Work… Where, When? Is it like transactions in ado.net?
As per the answer, i shouldn't create an abstraction layer over EF, but i want to keep my business layer independent. So i decided to go with the last option, adding TransactionScope. But i read, that it affects the performance. I have kept the IsolationLevel to ReadCommitted. But i am not sure about the performance.
So how can i use EF without adding its dependency to business layer.
My business objects are different from Entity objects.
If you don't want to draw a dependency on EF, you're going to have to abstract it out. The poster in the response you mentioned believes this is too much code, but if you want to decouple the data layer implementation from the business layer it's a necessary evil.
Historically I've gone with a relatively generic IRepository implementation that's generated from an IUnitOfWork such as:
uow.Get<IRepositoryType>()
By using an IoC container (using TinyIoC lately) we're able to handle and swap out our implementations easily, and keep our domain object separate from our data objects.

Adding functionality to my Entity Framework POCO classes

I've built a web application with Entity Framework using POCO.
I'm using these POCO classes as my business objects and not just for persisting data which works fine until...
Now I need to add some logic into these classes to do thing like total up sales, order lines, etc.
Should I add methods to my POCO classes to enable this functionality or leave them purely for persisting data and create some kind of 'processor' whereby I pass in the business objects and get the values I require out.
Is there a best practice for this?
What is the architectural design you are using or want to use?
For example, if these are your domain entities, you should put as much as possible logic in them. If they are merely data containers and you don't have a real architecture in place, your logic would probably in some business component.
So if you provide your question with some more details, we can help you better.

Why EF Entities are making a dependency and the need of POCO

I'm pretty new to IoC, Dependency Injection and Unit Testing. I'm starting a new pet project and I'm trying to do it right.
I was planning to use the Repository pattern to mediate with the data. The objects that I was going to return from the repositories were going to be objects collected from a Linq to entities data context (EF4).
I'm reading in "Dependency Injection" from Mark Seeman that doing it, makes an important dependency and will definitely complicate the testing (that's what he's using POCO objects in a Library Project).
I'm not understanding why. Although the objects are created by a linq to entities context, I can create them simply calling the constructor as they were normal objects. So I assume that is possible to create fake repositories that deviler these objects to the caller.
I'm also concerned about the automatic generation of POCO classes, which is not very easy.
Can somebody bring some light? Are POCO objects trully necessary for a decoupled and testable project?
**EDIT: Thanks to Yuck I understand that it's better to avoid autogeneration with templates, which brings me to a design question. If I come from a big legacy database wich his tables are assuming a variety of responsabilities (doesn't fit well with the concept of a class with a single responsability), what's the best way to deal with that?
Delete the database is not an option ;-)
No, they're not necessary it just makes things easier, cleaner.
The POCO library won't have any knowledge that it's being used by Entity Framework. This allows it to be used in other ways - in place of a view model, for instance. It also allows you to use the same project on both sides of a WCF service which eliminates the need to create data transfer objects (DTO).
Just two examples from personal experience but there are surely more. In general the less a particular object or piece of code knows about who is using it or how it's being used will make it more adaptable and generic for other situations.
You also mention automatic generation of POCO classes. I don't recommend doing this. Were you planning to generate the class definitions from your database structure?
I was planning to use the Repository pattern to mediate with the data.
The objects that I was going to return from the repositories were
going to be objects collected from a Linq to entities data context
(EF4).
The default classes (not the POCOs) EF generates contain proxies for lazy loading and are tied at the hip to Entity Framework. That means any other class that wants to use those classes will have to reference the required EF assemblies.
This is the dependency Mark Seeman is talking about. Since you are now dependent on these non-abstract types, which in turn are dependent on EF, you cannot simply change the implementation of your repository to something different (i.e. just using your own persistence store) without addressing this change in the class that depend on these types.
If you are truly only interested in the public properties of the EF generated types then you can have the partial classes generated by EF implement a base interface. Put all the properties you need in that base interface and pass the dependency in as the base interface - now you only depend on the base interface and not EF anymore.

Entity Data Framework and Web app architecture

I Am creating a web application and first use Entity Framework. I created Entity Data Model and now I am not sure, how to proceed now.
Premise: My database is really simple (Rating, WebPage, Visitor) and database tables corresponds to the business objects.
My suggestion is 3tier architecture but how to make it?
It is good idea create partial classes with the same name as Entity Framework objects (Rating, Visitor) and declare here new methods (GetAverageRating()...)? Or is better create some VisitorProvider, RatingProvider and place logic here?
It is better use EF objects in BLL and Presentation Layer or I should create my own BO objects on my BLL layer and transform EF object to BO?
I'm think, it is more practical use static methods on my DAL than instantiate classes on BLL. Do you agree?
Can you recommend me some best practices? I have many ideas how to create it, but I do not know what is the right.
3 layer architecture is quite popular but what it really means?
Presentation layer
Application layer
Database layer
If you ask what each layer means you can be pretty sure you will get several different answers. You can further divide each layer into sublayer and build layered hell like:
Client side presentation layer
Server side view layer
Controller layer
Service facade layer
Service layer
Domain objects layer
Repository + Factory layer
ORM layer
Stored procedure layer
Database view layer
Database table layer
WTF? That is just example that application can be easily over architected. It can go even worse if you insist that only neighbours can exchange data and if you decide to add special type of objects to be exchanged between layers instead of flowing sing set of objects through multiple layers.
Add layers which you need to make you more comfortable with developing the application and which will do reasonable separation of concerns and maintainability needed for the scale of your application. You can simply do the most simplest application which will be used just few weeks and must be developed as fast as possible. In such case you can do that within few days simply by using ASP.NET web forms and data source controls (or ASP.NET dynamic data). It can be badly extensible but in such situation it is exactly what you need to implement application quickly. Writing layers and doing all the stuff around maintainability and extensibility is reasonable if you need it. Another quick prototyping technique is ASP.NET MVC Scaffolding which can create quick multilayered skeleton of the application which can be further modified.
Both approaches are correct and it only depends on the approach you like. The first is called active record pattern but it is not used very often with entity framework. The second approach is more popular. You can either use EF directly in some middle class which you called Provider (common name is also Service). This class will do both data access logic and business logic. In more complex applications developers like to somehow wrap EF to separate class following repository pattern and call the repository either from service or directly from web app. code behind or controller (depending on amount of business logic). Try to do it without repository first. My personal opinion is that people should start to use repository only once they understand EF itself.
Again both approaches are correct. In a simple application it is fully acceptable to create EF model with POCO classes (EFv4.x) and use them in all layers. If you are using ASP.NET MVC you can find that you need special classes as view models to fully represent needs of your individual views. In a more complex application you can have separate objects exposed from a business layer - this is especially used if the business layer is exposed as a remote service (WCF).
It depends how you write these DAL methods - it is absolutely necessary to not share the EF context among requests! It also depends if you want to write some test or not. Layer defined by static methods is something which goes directly against testable architecture where you want unit test just single layer (unit testing with EF can be hard). It also depends if you want to use dependency injection which is based on instances.

Categories

Resources