Architecture of MVC application without using entity framework - asp.net-mvc

I am new in MVC application development.I am willing to develop a new project using MVC, i looked a lot for architectures that suits to MVC application.
After reading many articles and blogs i came to know that repository pattern can be used for this.
Based on my understanding before starting real project i created a dummy project structure like described below [ Not using EDMX file, entity framework in project, defined custom DAL ]
Name of my dummy application is Repository.I took Country,state and city relationship as example to develop dummy application :
Repository_DAL_V1 class library This library has class as below :
SQLHelper.cs : This class have methods to get executed for queries like ExecutenonQuery etc.
Repository_DTO_V1 class library This library has class as below :
CountryDTO.cs : This class is inherited from CountryModel.cs as [ CountryDTO:CountryModel ].This will be used to move data between all layers of application.If there is any property that is supposed to be used in business then this will be created in DTO not in model.
CountryDTOMapper.cs : This is used to map data from database in form of DataTable into collection of DTO object.
Repository_Implementation web mvc project This is UI Layer.
Repository_IRepositories_V1 class library This library has class as below :
ICountryRepository.cs : This is a interface having declared functions like SaveCountry() etc.
Repository_Models class library This library has class as below :
CountryModel.cs : This class has properties exactly for all columns of table in database.
Repository_Repositories_V1 class library This library has class as below :
CountryRepository.cs : This is a repository class having defined functions like SaveCountry() etc.
Repository_ViewModel_V1 class library This library has class as below :
CountryViewModel.cs : This will be build for Country View on screen.
above projects reference details :
Repository_DTO_V1 has reference of Repository_Models.
Repository_IRepositories_V1 has reference of Repository_DTO_V1,Repository_Models.
Repository_Repositories_V1 has reference of Repository_IRepositories_V1,Repository_DAL_V1,Repository_DTO_V1,Repository_Models.
Repository_ViewModel_V1 has reference of Repository_Repositories_V1,Repository_IRepositories_V1,Repository_DTO_V1,Repository_Models.
I need guidence from all of you to steer me in the right direction.

I don't se why not using EF would be any different from any other project you done layer wise that is. There is nothing wrong with you structure of things if you are comftable with using mulitple layers. I don't know what your project is about but you should consider better naming, like Project name (Repository) and Implementations is better named Web.
EDIT
I recommend you to use Entity Framework 5 with Code First, that is if you want to use a ORM?

I'm certainly with you on the desire to give EF a miss.
As #Dejan.S says, The architecture you'll need depends on the size of your project.
I would start off simple, perhaps with 3 projects:
A web project.
A service project that controllers use to access models and business logic.
A domain project with your models and data access.
If you need to separate things (like a DAL), you can still do that later.
Also, check out ServiceStack's MVC Power Pack. You get a great micro ORM, IoC, caching, fast serialisers and so on out of the box.

Related

What are Modules in aspnetBoilerplate?

aspnetBoilerplate is based on Domain Driven Design design pattern.
I see that aspnetBoilerplate compose an application using modules.
I didn't understand what a module is , i searched it's definition in the context of domain driven design and i found that it serves as a container for a specific set of classes of an application.
So does that means ,For example , in c# namespace is a module because it can contains many classes ?
But even with this definition , it's not clear in the context of aspnetBoilerplate, a module defintion in aspnetBoilerplate have this structure :
public class MyBlogApplicationModule : AbpModule
{
public override void Initialize()
{
IocManager.RegisterAssemblyByConvention(Assembly.GetExecutingAssembly());
}
}
so it's just one class,that have one method !
Also what is the relationship between model and dependency injection ?
Why there is a registration of the model as a service in an IocContainer?
Abp module is just a way for you to organize your code under the same domain/layer and at the same time still being able to configure/interact with other modules
E.g. your module is a separate library project that contains certain domain logic, to initialize your module correctly, you can place the initialization code in module life cycle hooks
Note: register DI in the life cycle hooks is an example of interacting with the DI service (that might be configured outside of your project)
See
https://aspnetboilerplate.com/Pages/Documents/Module-System#lifecycle-methods
Abp provides convenient way to register classes that follows the convention
IocManager.RegisterAssemblyByConvention(Assembly.GetExecutingAssembly());
Note: the recommended way is to only have a abp module per assembly
See
https://aspnetboilerplate.com/Pages/Documents/Dependency-Injection#registering-dependencies

Shorten Controller method in MVC

So I am writing an ASP.NET Core MVC application where users should be able to upload an Excel file, when a file gets uploaded I need to read the uploaded file an create a Model of the data inside the file.
I am currently creating this model in my Controller method but this made my method quite long.
My current solution is creating a class inside my Controller which deals with creating a model from an Excel file but I feel like this is the wrong way to do it.
So my question is: What is the right place to put the code that reads my excel file and puts it inside a model?
You should create a new .NET Standard library and create there the class that builds the model.
The recommended way is to use the class as an implementation and an interface (IExcelModelBuilder) that exposes all the public methods of that class (ExcelModelBuilder). This way you can inject this service into your controller constructor and, as a bonus, you can easily unit test it too.
You can read more about Dependency Injection in .NET Core.
You can register the service in your startup file:
// This method gets called by the runtime.
// Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
{...}
services.AddTransient<IExcelModelBuilder, ExcelModelBuilder>();
}
Step 1:Create a new .NET Standard library (Services)
Step 2:Add the reference into the mvc application of that library.
Step 3:Step two create a class that will be dealing with all the stuff like that if you have a limited number of tasks to perform ,
but if you want to separate it and wants a generic solution then Create an Interface (IUpload) and then implement all its methods in a class (Upload).also register the service in your startup file:

Project Structure in MVC design Pattern iOS

First of all i know MVC well and have been using it in project but when it comes to organizing classes and there role i am bit not sure of there proper implementation. Lets take a scenario to proceed with:
A sample which will display All Employee and Department. Data will be fetched from Web Services(Json) and will be stored as offline(Core Data).
So MVC pattern would be:
View will be my storyboard with Employee and Department UIViewController.
Controller will be EmployeeViewController.swift and DepartmentViewController.swift
Model will be Employee.swift and Department.swift
class Employee: NSObject {
var name: String?
}
class Department: NSObject {
var departmentName: String?
}
ServiceManager which will make calls to the web service.
ParseData which will parse the web service response and convert it into Employee and Department objects
CoreDataManager is singleton class to manage CRUD operation on offline DB.
Here are series of question on the above scenario which i have:
Is my understanding correct? Is the structure which i am trying to build follows proper MVC?
How the controller will interact with these components (Service Manager, ParseData, CoreDataManager). Should there be another class which will facilitate the communication between controller and data management(if controller does this then it will a tightly-coupled structure and massive as well).
Should Model be having any code other then property and initialization method as most of the model which i have seen only have property declaration?
Should there be separate UIView classes instead of storyboard to create a proper MVC structure?
Is my understanding correct? Is the structure which i am trying to
build follows proper MVC?
First I will say that "proper" MVC will depend on who you're asking. Its origin is commonly attributed to Trygve Reenskaug when he introduced this into Smalltalk in the 70's. However, his type of MVC was widely different from the bloated versions most commonly used today. The modern way of thinking about MVC is
Model = mostly a dumb class which primarily encapsulates data
View = whatever we present on the screen
Controller = the big lump of code that does almost everything,
sometimes offloaded by a manager class or two of some sort
Reenskaug, however, would have a model and a view and a controller for a button. For a label. For a field. I'm not saying that is what we should strive for, but there should be better ways to structure a project than using the Massive ViewController pattern (as it is jokingly referred to in the iOS community).
Luckily, there are.
Uncle Bob is preaching Clean Architecture. There are several implementations of this, and various people have made their own implementations of this for iOS, like VIPER and Clean Swift.
How the controller will interact with these components (Service
Manager, ParseData, CoreDataManager). Should there be another class
which will facilitate the communication between controller and data
management(if controller does this then it will a tightly-coupled
structure and massive as well).
Following the principles of Clean Architecture, you should encapsulate these functionalities into layers, in a way that enables you not just to split the code into multiple components, but also enables you to replace them with other components when that is needed. (But yes, at the very least avoid putting all of this in your controller!)
Should Model be having any code other then property and initialization
method as most of the model which i have seen only have property
declaration?
Again, there is not a single answer here. Some proponents of "real" OOP will say that each object should be self-served (i.e. a model object should know how to persist itself), while others extract the knowledge of such operations into "managers". Putting code to persist an object into the object could mean littering persistence functionality into many objects, or require you to rely on subclassing or other solutions to avoid this coupling.
Should there be separate UIView classes instead of storyboard to
create a proper MVC structure?
Storyboard or not does not determine whether you're using "proper" MVC. Also, what kind of class you're choosing (UIView or UIViewController) to represent the View is also not important. Your ViewController can be dumbed down to such a degree that it contains no logic (forwarding the logic that it DOES have to another class, i.e. the Presenter in VIPER).
I would recommend reading about the Clean Architecture and maybe watch a video of Uncle Bob explaining it, read other people's reports on implementing it, and then consider whether MVC is the correct pattern for your iOS project.

ControllerFactory : Entity Framework

I recently followed Stephen Walther through creating a generic repository for your data models using the Entity Framework with the following link, http://bit.ly/7BoMjT
In this blog he briefly talks about creating a generic repository and why it's suggested to do so (to be clear of friction). The blog itself doesn't go into great detail on how to inject the GenericRepository into your project for that you'll need to download his source code of Common Code. However, once I finally understood the importance of the Repository pattern, and how it makes a difference in the data models I create in ASP.Net MVC I was wondering if I could do something similar to my Controllers and Views?
Can I create a ControllerRepository or ControllerFactory(as I've Bing'd it) and create a generic controller with 5 ActionResults and depending on what I inject into my GenericRepository datamodel (i.e. I have DellXPSComputers, GateWayComputers, HPComputers as a single db datamodel)
And actually have only one controller besides the Generic one I create that will go and grab the right datamodel, and view?
If so, what is the best way to implement this?
You could create a generic controller factory, but I don't see many scenarios why you'd ever want to. Except in your tests and redirects, you'd never be calling a controller method directly (vs. a repository method which you're calling in many places).
Yes! You absolutely can!
I've done it in the past with great success. The result is that you end up with a web application layer surfacing your repos with almost no code (just what's necessary to provide CRUD services for your entities).
Ultimately, you'll end up with something like this in your implementation of CreateController:
Type controllerType = controllerbase.MakeGenericType(entityType, datacontextType);
var controller = Activator.CreateInstance(controllerType) as IController;
return controller;
Wiser men than me would use a IOC framework to inject the types, I'm using plain old reflection and reading the type names out of the route values in URLs like:
http://computer/repo/entityname/by/fieldname/value.html
Good luck!

Access to Entity Manager in ASP .NET MVC

Greetings,
Trying to sort through the best way to provide access to my Entity Manager while keeping the context open through the request to permit late loading. I am seeing a lot of examples like the following:
public class SomeController
{
MyEntities entities = new MyEntities();
}
The problem I see with this setup is that if you have a layer of business classes that you want to make calls into, you end up having to pass the manager as a parameter to these methods, like so:
public static GetEntity(MyEntities entityManager, int id)
{
return entityManager.Series.FirstOrDefault(s => s.SeriesId == id);
}
Obviously I am looking for a good, thread safe way, to provide the entityManager to the method without passing it. The way also needs to be unit testable, my previous attempts with putting it in Session did not work for unit tests.
I am actually looking for the recommended way of dealing with the Entity Framework in ASP .NET MVC for an enterprise level application.
Thanks in advance
Entity Framework v1.0 excels in Windows Forms applications where you can use the object context for as long as you like. In asp.net and mvc in particular it's a bit harder. My solution to this was to make the repositories or entity managers more like services that MVC could communicate with. I created a sort of generic all purpose base repository I could use whenever I felt like it and just stopped bothering too much about doing it right. I would try to avoid leaving the object context open for even a ms longer than is absolutely needed in a web application.
Have a look at EF4. I started using EF in production environment when that was in beta 0.75 or something similar and had no real issues with it except for it being "hard work" sometimes.
You might want to look at the Repository pattern (here's a write up of Repository with Linq to SQL).
The basic idea would be that instead of creating a static class, you instantiate a version of the Repository. You can pass in your EntityManager as a parameter to the class in the constructor -- or better yet, a factory that can create your EntityManager for the class so that it can do unit of work instantiation of the manager.
For MVC I use a base controller class. In this class you could create your entity manager factory and make it a property of the class so deriving classes have access to it. Allow it to be injected from a constructor but created with the proper default if the instance passed in is null. Whenever a controller method needs to create a repository, it can use this instance to pass into the Repository so that it can create the manager required.
In this way, you get rid of the static methods and allow mock instances to be used in your unit tests. By passing in a factory -- which ought to create instances that implement interfaces, btw -- you decouple your repository from the actual manager class.
Don't lazy load entities in the view. Don't make business layer calls in the view. Load all the entities the view will need up front in the controller, compute all the sums and averages the view will need up front in the controller, etc. After all, that's what the controller is for.

Resources