Entity Framework circular dll reference - c#

My solution in it's current (sad) state:
I want my business layer data-provider agnostic (isn't that a good thing?) with just an interface so I can switch out EF with NHibernate or Linq to Xml or whatever type of persistance provider me or my boss wants to use (or the new superior one that will inevitably be invented 2 seconds after this project is all done).
IPersistenceProvider is that interface, and I can just inject it with Unity (not the gaming platform, the DI container). To me, IPersistenceProvider belongs in the Data Layer and we can just keep adding folders (like EntityFramework) as new persistence paradigms are needed to be added to my resume (or the project).
Therefore, my business dll depends on my data dll. Here's some code in the business dll, depending on the data dll:
using System;
using Atlas.Data.Kernel;
namespace Atlas.Business.Kernel
{
public abstract class BusinessObject
{
public BusinessObject(IPersistenceProvider p)
{
}
public Guid Id;
}
}
I also feel like my DatabaseContext belongs in the Data Layer. But EF makes you reference the concrete types for its DbSets, which means the AtlasDataKernel dll would need to depend on the AtlasBusinessKernel dll, which would make a circular dll reference. En plus (that's French for moreover), a Data Layer thingy pointing to the Business Layer concrete types smells to me. DatabaseContext wants to go live in the business dll, but that's coupling my business layer with a particular persistence strategy artifact.
How to resolve this? I can collapse it into one dll (and indeed, I did that very thing on a previous project), but that kinda sucks and I won't be able to get into the .Net Architects club. They will mock me for my "1 N too few" architecture and laugh me out of the meeting. WWDED? (What would Dino Esposito Do?)

Split declaration from implementation.
The EntityFramework subdirectory should be a separate assembly (e.g. AtlasDataKernelEF) containing the EF stuff and the implementation of IPersistenceProvider, thus resolving the circular reference.
Also, if you should really get required to use a different ORM, you getyour production executables rid of all EF libraries.
You don't sketch how you instantiate EF data access, but you certainly need to wrap that in some kind of factory class.

Your project AtlasBusinessKernel shouldn't reference any resources in the AtalsDataKernal class. Any resources in the AtalsDataKernal that the AtalsBusinessKernel needs to use should be represented as an interface in the AtalasBusinessKernal project, could be an IDataConext interface or repository interfaces.
This only works if you have a third project which actually using the AtalsBusinessKernal project, perhaps a web application or a console application that represents the UI. This project would be responsible for instantiating the DatabaseContext, preferably using DI.
// In your AtlasDataKernal
public class DatabaseContext : IDataContext
{
// implementation
}
// In your AtlasBusinessKernal
public class MyBusinessLogic
{
private IDataContext dataContext;
public MyBusinessLogic(IDataContext context)
{
this.dataContext = context;
}
}
// In your web application or whatever project type it might be
public class MyWebApp
{
public DoSomeThing()
{
IDataContext context = new DatabaseContext();
MyBusinessLogic logic = new MyBusinessLogic(context);
}
}

Related

Repository Pattern with IoC

I am building a WPF application (storage system), which would be running for a very long time and therefore I am interested in what option should I go with when using Entity Framework with Repository Patterns.
What I did, is that I have separated my Data Access Layer (DAL) into a separate class library referenced by the main project. For the technologies, I have decided to use Entity Framework 6 & SQLite database (plus SQLite plugins for EF).
In the main project, except for other things (such as Prism) I am also using Unity for IoC while working with my ViewModels.
This is how I am registering my repository under Bootstrapper.cs class:
Container.RegisterType<IUserRepository, UserRepository>(new TransientLifetimeManager());
The reason why I have decided to use TransientLifetimeManager was to make sure, that this class is re-created every time ViewModel is created and thus ensuring that new data is being fetched from the database.
Here is a (oversimplified) repository with only two methods:
public interface IUserRepository
{
UserLevel TryLoginUser(User user);
string RegisterNewUser(User user);
void Dispose();
}
With sample implementation:
public class UserRepository : IUserRepository
{
public enum UserLevel { Regular, Supervisor, Admin, Invalid };
private readonly DataContext _context;
public UserRepository()
{
_context = new DataContext();
}
public UserLevel TryLoginUser(User user)
{
return UserLevel.Invalid;
}
public string RegisterNewUser(User user)
{
return null;
}
}
What users will be doing is, that they will be switching between 2 (or three) main windows thorough the lifetime of an application. In order to make sure, that the database data from Entity Framework is in sync with the database, what I have decided to do is to initialize new DataContext in the constructor of the method itself (which reloads the data).
When I have explored the memory usage while navigating back and forth between my windows (and calling various repositories), I have noticed that the memory usage starts to go up, which means that, clearly, there is something wrong with my method of initializing and injecting Repositories.
Finally, in regards to this topic, I have also tried to somehow register my DataContext.cs (which is very simple and just inherits from DbContext) so that it could be injectable into the repositories; however I had even problems registering it (as it lacks interface definition, Unity didn't allow me to register it).
I would highly appreciate any help or recommendations in this matter.

C# Dependency Injection with 3 projects on same Solution

I have a solution with separate projects. The structure is like this:
1 - the web project
2 - the Aplicacao, that is called by the controllers of 1 to do the logic
3 - the Dominio, that has the classes of my solution
4 - the Dados, that has the entity framework stuff...
So, when I have a POST to register a new user, the UsuarioController (UC) is called. The UC has to instanciate a UsuarioAplicacao (UA) passing a usuario. The UA has to instanciate a UsuarioRepositorio (UR) passing a usuario as parameter and here it will be salved to the database.
I'm used to instanciate the class I need inside the constructor of the class, like so:
public ActionResult Registrar (Usuario usuario)
{
if (ModelState.IsValid)
{
var _usuarioApp = new UsuarioAplicacao();
_usuarioApp.Salvar(usuario);
rest of the code...
}
}
But, while studing, I've learned that this isn't quite right. I should use the dependency injection (DI)...
So, using DI with the constructor, I can't figure out how to do it...
I've tried like this in my controller:
private UsuarioAplicacao _usuarioAplicacao;
public UsuarioController (UsuarioAplicacao usuarioAplicacao)
{
this._usuarioAplicacao = usuarioAplicacao;
}
then, on my UsuarioAplicacao (class that do the logics and call UsuarioRepositorio to save the object into the DB):
private readonly UsuarioRepositorio _usuarioRepositorio;
public UsuarioAplicacao (UsuarioRepositorio usuarioRepositorio)
{
this._usuarioRepositorio = usuarioRepositorio;
}
and finnaly, inside my UsuarioRepositorio (class responsable for saving tha data into the DB via Entity Framework):
private readonly Contexto _contexto;
public UsuarioRepositorio(Contexto contexto)
{
this._contexto = contexto;
}
(_contexto is my EF context class)
These are my onstructors. But I'm getting Null Reference Exceptions...
Can you guys help me with dependency injection?
Ninject I couldn't understand how to use either...
thanks in advance
you are getting null references because you didn't configure any dependency injection. Simply passing a parameter on the controller constructor is not enough, you have to actually tell the depedency injector how to construct your dependencies.
Using Unity, you do something like this on your WebApiConfig (or global.asax if on mvc)
public static void UnityContext_OnRegisterComponents(Microsoft.Practices.Unity.UnityContainer container)
{
container.RegisterType<ICarRepository, CarRepository>(new HierarchicalLifetimeManager());
}
Now, for the concept of dependency injection, it is used to keep low coupling among projects. Your controller must not know your Business rules, neither how to create objects that belong to another assembly.
Example: When you create your repositories and isntantiate your entities directly on the controller, you are creating a dependency between those assemblies, making it really hard to test your code later, also making it a lot more complex.
In terms of architecture, I use something like this:
Web - Front end
Business - Where you do your business Rules
Contracts - Where you declare your data transfer objects
Data - Where you declare your entities, and entity framework do low level stuff, like opening connections, saving things to the database and etc, and where you declare your repositories
In that architeture:
Web access Contracts and Business
Business access Contracts and Data
Data Doesnt Access Anything
Business will ask Data for entities, Data will answer with the entity models from your database, and any manipulation you need to do, will be done in the business, returning a data transfer object (of the Contracts assembly), which will them be used in your front end, either as it is returned, or defining a new model to fit the transfer object into your front end.
In this scenario, keeping dependency injection in mind, it would create a coupling if the business layer knew how to create Data Layer objects, so instead of doing this, you configura a dependency injection container, and that object will be responsible for instantiating everything that every layer needs, keeping all your projects decoupled.

LINQ to SQL and N-Tier layering

My experience has made me more accustomed to the following structure in my programs. Let's say it is a .NET WPF application. You create a WPF project, a Business Logic project (Class Library), a Data Access project (Class Library), and an Entities project (Class Library). The WPF project goes through the Business Logic Layer to the Data Access Layer. The Entities are lightweight DTOs and can flow freely from layer to layer.
My question is this. I like LINQ to SQL entities, except if I use it to create my entities, I not only wind up with a straight table to entities relationship, it also puts my Entities in my Data Access project and forces my UI project to have a reference to my Data Access project. Granted, I can make my DataContext internal (which I think it should be by default anyhow), except my DTOs are still in my Data Access project and it still forces my UI project to have a reference to my Data Access project.
Am I missing something here or is there another way to extricate my DTOs with LINQ to SQL or should I even care?
If we follow a Dependency inversion principle
High level modules should not depend upon low-level modules. Both should depend upon abstractions.
Abstractions should never depend upon details. Details should depend upon abstractions.
So in your case UI and Business logic should not depend upon Data access. Abstracted entities should never depend upon details of LINQ to SQL
Then we start design our application from high level layers
1 Create Project of entities abstractions
public interface ICustomer
{
int Id { get; set; }
}
2 Create Project business logic abstractions used by UI project
public interface ICustomerService
{
List<ICustomer> LoadTop50();
}
3 Create UI project
3.1 Create UI logic which use ICustomer and ICustomerService for showing person information
Notice: UI depends only on abstractions and have no knowledge about other layers.
4 Create Business project
4.1 Create DataAccess abstraction for fetching data
namespace Business.DataAccessAbstractions
{
public interface ICustomerDataAccess
{
List<ICustomer> Load(int topAmount);
}
}
4.2 Implement ICustomerService which use abstractions of ICustomerDataAccess
public class CustomerService : ICustomerService
{
private DataAccessAbstractions.ICustomerDataAccess _dataAccess;
public CustomerService(DataAccessAbstractions.ICustomerDataAccess dataAccess)
{
_dataAccess = dataAccess;
}
public IEnumerable<ICustomer> LoadTop50()
{
const int TOP_NUMBER = 50;
return _dataAccess.Load(TOP_NUMBER);
}
}
Notice: Business project create abstractions for data access. And implement abstractions, which UI will use for showing data.
5 Create DataAccess project
5.1 Create entities with LINQ to SQL.
5.2 Implement Business.DataAccessAbstractions.ICustomerDataAccess interface.
5.2.1 Make entities, generated by LINQ to SQL, implement ICustomer
[Table(Name="dbo.Customer")]
public partial class Customer : INotifyPropertyChanging,
INotifyPropertyChanged,
ICustomer
{
private int _Id;
[Column(Storage="_Id",
AutoSync=AutoSync.OnInsert,
DbType="Int NOT NULL IDENTITY",
IsPrimaryKey=true,
IsDbGenerated=true)]
public int Id
{
get
{
return this._Id;
}
set
{
if ((this._Id != value))
{
this.OnIDChanging(value);
this.SendPropertyChanging();
this._Id = value;
this.SendPropertyChanged("Id");
this.OnIDChanged();
}
}
}
}
You need only add ICustomer to the list of implemented interfaces. Or create/generate some "mapping logic" which convert entities generated by LINQ to SQL to the instances which will impelement ICustomer. I found that adding ICustomer was easiest way for this sample.
Notice: DataAccess project have dependencies only on abstractions which is implemented by using LINQ to SQL
6 Create Main project which will compound all dependencies together and launch your UI.
Notice: This project will have all references needed for your application to work properly.
Summary
With this approach you UI will not depend on details of LINQ to SQL.
With this approach you can freely modify your implementation of DataAccess until modifications will not break high level abstractions.
Of course if you decide to add new data field for Customer, which you want use in UI, then you need to modify whole chain of dependencies.

Relationship between EF-Generated classes and model?

I'm using ASP .NET MVC (C#) and EntityFramework (database first) for a project.
Let's say I'm on a "Movie detail" page which shows the detail of one movie of my database. I can click on each movie and edit each one.
Therefore, I have a Movie class, and a Database.Movie class generated with EF.
My index action looks like :
public ActionResult MovieDetail(int id)
{
Movie movie = Movie.GetInstance(id);
return View("MovieDetail", movie);
}
GetInstance method is supposed to return an instance of Movie class which looks like this for the moment :
public static Movie GetInstance(int dbId)
{
using (var db = new MoviesEntities())
{
Database.Movie dbObject = db.Movies.SingleOrDefault(r => r.Id == dbId);
if (dbObject != null)
{
Movie m = new Movie(dbObject.Id, dbObject.Name, dbObject.Description);
return m;
}
return null;
}
}
It works fine but is this a good way to implement it? Is there an other cleaner way to get my instance of Movie class ?
Thanks
is this a good way to implement it?
That's a very subjective question. It's valid, and there's nothing technically wrong with this implementation. For my small-size home projects, I've used similar things.
But for business applications, it's better to keep your entities unrelated to your MVC application. This means that your data context + EF + generated entities should be kept in a separate project (let's call it the 'Data' project), and the actual data is passed in the form of a DTO.
So if your entity resembles this:
public class Person {
public int Id { get; set; }
public string Name { get; set; }
}
You'd expect there to be an equivalent DTO class that is able to pass that data:
public class PersonDTO {
public int Id { get; set; }
public string Name { get; set; }
}
This means that your 'Data' project only replies with DTO classes, not entities.
public static MovieDTO GetInstance(int dbId)
{
...
}
It makes the most sense that your DTOs are also in a separate project. The reason for all this abstraction is that when you have to change your datacontext (e.g. the application will start using a different data source), you only need to make sure that the new data project also communicates with the same DTOs. How it works internally, and which entities it uses, is only relevant inside the project. From the outside (e.g. from your MVC application), it doesn't matter how you get the data, only that you pass it in a form that your MVC projects already understand (the DTO classes).
All your MVC controller logic will not have to change, because the DTO objects haven't changed. This could save you hours. If you link the entity to your Controller AND View, you'll have to rewrite both if you suddenly decide to change the entity.
If you're worried about the amount of code you'll have to write for converting entities to DTOs and vice versa, you can look into tools like Automapper.
The main question: Is this needed?
That, again, is a very subjective question. It's relative to the scope of the project, but also the expected lifetime of the application. If it's supposed to be used for a long time, it might be worth it to keep everything interchangeable. If this is a small scale, short lifetime project, the added time to implement this might not be worth it.
I can't give you a definitive answer on this. Evaluate how well you want the application to adapt to changes, but also how likely it is that the applicaiton will change in the future.
Disclaimer: This is how we do it at the company where I work. This is not the only solution to this type of problem, but it's the one I'm familiar with. Personally, I don't like making abstractions unless there's a functional reason for it.
A few things:
The naming you're using is a little awkward and confusing. Generally, you don't ever want to have two classes in your project named the same, even if they're in different namespaces. There's nothing technically wrong with it, but it creates confusion. Which Movie do I need here? And if I'm dealing with a Movie instance, is it Movie or Database.Movie? If you stick to names like Movie and MovieDTO or Movie and MovieViewModel, the class names clearly indicate the purpose (lack of suffix indicates a database-backed entity).
Especially if you're coming from another MVC framework like Rails or Django, ASP.NET's particular flavor of MVC can be a little disorienting. Most other MVC frameworks have a true Model, a single class that functions as the container for all the business logic and also acts as a repository (which could be considered business logic, in a sense). ASP.NET MVC doesn't work that way. Your entities (classes that represent database tables) are and should be dumb. They're just a place for Entity Framework to stuff data it pulls from the database. Your Model (the M in MVC) is really more a combination of your view models and your service/DAL layer. Your Movie class (not to be confused with Database.Movie... see why that naming bit is important) on the other hand is trying to do triple duty, acting as the entity, view model and repository. That's simply too much. Your classes should do one thing and do it well.
Again, if you have a class that's going to act as a service or repository, it should be an actual service or repository, with everything those patterns imply. Even then, you should not instantiate your context in a method. The easiest correct way to handle it is to simply have your context be a class instance variable. Something like:
public class MovieRepository
{
private readonly MovieEntities context;
public MovieRepository()
{
this.context = new MovieEntities();
}
}
Even better, though is to use inversion of control and pass in the context:
public class MovieRepository
{
private readonly MovieEntities context;
public MovieRepository(MovieEntities context)
{
this.context = context;
}
}
Then, you can employ a dependency injection framework, like Ninject or Unity to satisfy the dependency for you (preferably with a request-scoped object) whenever you need an instance of MovieRepository. That's a bit high-level if you're just starting out, though, so it's understandable if you hold off on going the whole mile for now. However, you should still design your classes with this in mind. The point of inversion of control is to abstract dependencies (things like the context for a class that needs to pull entities from the database), so that you can switch out these dependencies if the need should arise (say perhaps if there comes a time when you're going to retrieve the entities from an Web API instead of through Entity Framework, or even if you just decide to switch to a different ORM, such as NHibernate). In your code's current iteration, you would have to touch every method (and make changes to your class in general, violating open-closed).
entity-model never should act as view-model. Offering data to the views is an essential role of the view-model. view-model can easily be recognized because it doesn’t have any other role or responsibility other than holding data and business rules that act solely upon that data. It thus has all the advantages of any other pure model such as unit-testability.
A good explanation of this can be found in Dino Esposito’s The Three Models of ASP.NET MVC Apps.
You can use AutoMapper
What is AutoMapper?
AutoMapper is a simple little library built to solve a deceptively complex problem - getting rid of code that mapped one object to another. This type of code is rather dreary and boring to write, so why not invent a tool to do it for us?
How do I get started?
Check out the getting started guide.
Where can I get it?
First, install NuGet. Then, install AutoMapper from the package manager console:
PM> Install-Package AutoMapper

Design issue with interaction between Service Layer and DAL Layer

I have a design problem with my poject that I don't know how to fix, I have a DAL Layer which holds Repositories and a Service Layer which holds "Processors". The role of processors is to provide access to DAL data and perform some validation and formatting logic.
My domain objects all have a reference to at least one object from the Service Layer (to retrieve the values of their properties from the repositories). However I face two cyclical dependencies. The first "cyclical dependency" comes from my design since I want my DAL to return domain objects - I mean that it is conceptual - and the second comes from my code.
A domain object is always dependent of at least one Service Object
The domain object retrieves his properties from the repositories by calling methods on the service
The methods of the service call the DAL
However - and there is the problem - when the DAL has finished his job, he has to return domain objects. But to create these objects he has to inject the required Service Object dependencies (As these dependencies are required by domain objects).
Therefore, my DAL Repositories have dependencies on Service Object.
And this results in a very clear cyclical dependency. I am confused about how I should handle this situation. Lastly I was thinking about letting my DAL return DTOs but it doesn't seem to be compatible with the onion architecture. Because the DTOs are defined in the Infrastructure, but the Core and the Service Layer should not know about Infrastucture.
Also, I'm not excited about changing the return types of all the methods of my repositories since I have hundreds of lines of code...
I would appreciate any kind of help, thanks !
UPDATE
Here is my code to make the situation more clear :
My Object (In the Core):
public class MyComplexClass1
{
MyComplexClass1 Property1 {get; set;}
MyComplexClass2 Property2 {get; set;}
private readonly IService MyService {get; set;}
public MyComplexClass1(IService MyService)
{
this.MyService = MyService;
this.Property1 = MyService.GetMyComplexClassList1();
.....
}
This is my Service Interface (In the Core)
public interface IService
{
MyComplexClass1 GetMyComplexClassList1();
...
}
This my Repository Interface (In the Core)
public interface IRepoComplexClass1
{
MyComplexClass1 GetMyComplexClassObject()
...
}
Now the Service Layer implements IService, and the DAL Layer Implements IRepoComplexClass1.
But my point is that in my repo, I need to construct my Domain Object
This is the Infrascruture Layer
using Core;
public Repo : IRepoComplexClass1
{
MyComplexClass1 GetMyComplexClassList1()
{
//Retrieve all the stuff...
//... And now it's time to convert the DTOs to Domain Objects
//I need to write
//DomainObject.Property1 = new MyComplexClass1(ID, Service);
//So my Repository has a dependency with my service and my service has a dependency with my repository, (Because my Service Methods, make use of the Repository). Then, Ninject is completely messed up.
}
I hope it's clearer now.
First of all, typically architectural guidance like the Onion Architecture and Domain Driven Design (DDD) do not fit all cases when designing a system. In fact, using these techniques is discouraged unless the domain has significant complexity to warrant the cost. So, the domain you are modelling is complex enough that it will not fit into a more simple pattern.
IMHO, both the Onion Architecture and DDD try to achieve the same thing. Namely, the ability to have a programmable (and perhaps easily portable) domain for complex logic that is devoid of all other concerns. That is why in Onion, for example, application, infrastructure, configuration and persistence concerns are at the edges.
So, in summary, the domain is just code. It can then utilize those cool design patterns to solve the complex problems at hand without worrying about anything else.
I really like the Onion articles because the picture of concentric barriers is different to the idea of a layered architecture.
In a layered architecture, it is easy to think vertically, up and down, through the layers. For example, you have a service on top which speaks the outside world (through DTOs or ViewModels), then the service calls the business logic, finally, the business logic calls down to some persistence layer to keep the state of the system.
However, the Onion Architecture describes a different way to think about it. You may still have a service at the top, but this is an application service. For example, a Controller in ASP.NET MVC knows about HTTP, application configuration settings and security sessions. But the job of the controller isn't just to defer work to lower (smarter) layers. The job is to as quickly as possible map from the application side to the domain side. So simply speaking, the Controller calls into the domain asking for a piece of complex logic to be executed, gets the result back, and then persists. The Controller is the glue that is holding things together (not the domain).
So, the domain is the centre of the business domain. And nothing else.
This is why some complain about ORM tools that need attributes on the domain entities. We want our domain completely clean of all concerns other than the problem at hand. So, plain old objects.
So, the domain does not speak directly to application services or repositories. In fact, nothing that the domain calls speaks to these things. The domain is the core, and therefore, the end of the execution stack.
So, for a very simple code example (adapted from the OP):
Repository:
// it is only infrastructure if it doesn't know about specific types directly
public Repository<T>
{
public T Find(int id)
{
// resolve the entity
return default(T);
}
}
Domain Entity:
public class MyComplexClass1
{
MyComplexClass1 Property1 {get; } // requred because cannot be set from outside
MyComplexClass2 Property2 {get; set;}
private readonly IService MyService {get; set;}
// no dependency injection frameworks!
public MyComplexClass1(MyComplexClass1 property1)
{
// actually using the constructor to define the required properties
// MyComplexClass1 is required and MyComplexClass2 is optional
this.Property1 = property1;
.....
}
public ComplexCalculationResult CrazyComplexCalculation(MyComplexClass3 complexity)
{
var theAnswer = 42;
return new ComplexCalculationResult(theAnswer);
}
}
Controller (Application Service):
public class TheController : Controller
{
private readonly IRepository<MyComplexClass1> complexClassRepository;
private readonly IRepository<ComplexResult> complexResultRepository;
// this can use IoC if needed, no probs
public TheController(IRepository<MyComplexClass1> complexClassRepository, IRepository<ComplexResult> complexResultRepository)
{
this.complexClassRepository = complexClassRepository;
this.complexResultRepository = complexResultRepository;
}
// I know about HTTP
public void Post(int id, int value)
{
var entity = this.complexClassRepository.Find(id);
var complex3 = new MyComplexClass3(value);
var result = entity.CrazyComplexCalculation(complex3);
this.complexResultRepository.Save(result);
}
}
Now, very quickly you will be thinking, "Woah, that Controller is doing too much". For example, how about if we need 50 values to construct MyComplexClass3. This is where the Onion Architecture is brilliant. There is a design pattern for that called Factory or Builder and without the constraints of application concerns or persistence concerns, you can implement it easily. So, you refactor into the domain these patterns (and they become your domain services).
In summary, nothing the domain calls knows about application or persistence concerns. It is the end, the core of the system.
Hope this makes sense, I wrote a little bit more than I intended. :)

Categories

Resources