Interface in Mvc Project, Implementing in Data Project - circular reference? - asp.net-mvc

I'm developing an mvc application just to practice some best practices (trying to do everything the 'correct' way). To be more precise, I thought of building an MVC Application with some ajax endpoints for a chat service.
I wanted to have that one a little more flexible, so I thought of using interfaces to define the structure of used objects. Those interfaces should then be implemented by the DataLayer Project.
Now I wanted to define those interfaces in the Mvc-Project and put the datalayer stuff in a separate project. This would lead to a circular reference though, which I thought of as bad practice.
What is the 'correct' way to solve this issue? Is my approach reasonable?
Some code to show what I want to archive:
Mvc Project:
public interface IChatUser
{
Guid UserID { get; }
string Name { get; }
}
Datalayer Project (part of class):
public class User : IChatUser
{
private Guid _userID;
public Guid UserID
{
get
{
return _userID;
}
}
public string Name
{
get
{
return this.LastName + " ," + this.FirstName;
}
}
}

Is there a reason you aren't just using NHibernate? If you are then your controllers just have access to a Session object for any basic queries you want to run.
Complex stuff gets broken out into separate query or command objects.
We built a full MVC app using the stuff discussed here: http://ayende.com/blog/154081/limit-your-abstractions-you-only-get-six-to-a-dozen-in-the-entire-app and were very happy with the results.

Related

Entity framework 6 providing repositories and UoW out of the box

But how do you use it?
I have a Code First project set up, and trying out some stuff with this new EF6. Reading all kinds of posts/blogs from at least 2 years old about EF4/5. But nothing whatsoever about EF6.
Let's say I have these entities:
public DbSet<Person> Persons { get; set; }
public DbSet<Order> Orders { get; set; }
public DbSet<Invoice> Invoices { get; set; }
Do I still need to create repositories for each entity? Or would a class suffice with some methods to do some custom calculations aside from CRUD?
I know that this line:
kernel.Bind<MyDbContext>().ToSelf().InRequestScope();
Would suffice for DI, and that it will inject via constructor to upper layer classes where applicable.
The project has a class library and a web project asp.net-mvc. Where the class lib project contains my entities and has Migrations enabled.
Any light on this matter is really appreciated.
I've added a Repository layer on top of EF (which utilizes both Repository and UoW patterns inherently in its construction) in a couple of projects, and I've done that with one class that utilizes generics so that I only needed one file for all of my entities. You can decide if you want to do it or not, but I've found it useful in my projects.
My repositories have typically started out like what I've shown below, following up with more extension methods if/when I come across a need for them (obviously I'm not showing all of them, that's up for you to decide how to implement your repository).
public class Repository<T> : IRepository<T> where T : class
{
protected IDbContext Context;
protected DbSet<T> DbSet { get { return Context.Set<T>(); } }
public Repository(IDbContext context = null)
{
Context = context ?? new DbContext();
}
public void Add(T newRecord)
{
DbSet.Add(newRecord);
}
public void Update(T record)
{
var entry = Context.Entry(record);
DbSet.Attach(record);
entry.State = EntityState.Modified;
}
public void Remove(T record)
{
Context.Entry(record).State = EntityState.Deleted;
DbSet.Remove(record);
}
public IQueryable<T> Where(Expression<Func<T, bool>> predicate)
{
return DbSet.Where(predicate);
}
public bool Contains(Expression<Func<T, bool>> predicate)
{
return DbSet.Count(predicate) > 0;
}
public int Count(Expression<Func<T, bool>> predicate)
{
return DbSet.Count(predicate);
}
public int Save()
{
return Context.SaveChanges();
}
}
I've used repositories for 2 main reasons:
Unit testing. Doing this pattern allows me to fake the underlying data without having to have bad data in my database. All I need to do is simply create another implementation of IRepository that uses an in-memory list as its data source, and I'm all set for my pages to query that repository.
Extensibility. A fair number of times I've put in some methods into my repository because I found myself constantly doing the same logic with queries in my controllers. This has been extremely useful, especially since your client-side code doesn't need to know how it's doing it, just that it is doing it (which will make it easier if you need to change the logic of one file vs. multiple files).
This not all of it, obviously, but that should be enough for this answer. If you want to know more on this topic, I did write a blog post on it that you can find here.
Good luck on whatever you decide to do.
Entity Framework in itself can be considered a Repository. It facilitates work with data, in this case a database. This is all that a Repository does.
If you want to build another Repository on top of what EF provides, it is completely up to you - or to your business rules.
Many complex projects uses 2-3 layers of repositories with web services between. The performance is lower but you gain on other plans like security, resilience, separation of concerts, etc.
Your company might decide that it's in their best interest to never access data directly from front-end projects. They might force you to build a separate web-service project, which will be accessible only from localhost. So you will end up having EF as Repository in the webservice project. On the front-end side you will obviously need to build another Repository which will work with the web-service.
It also depends a lot of your project. If it's a small project it really it's overkill to build a second Repository on top of EF. But then again, read above. Nowadays security matters a lot more than performance.
To be politically correct I'm including the comment made by Wiktor Zychla:
"DbSet is a repository and DbContext is a Unit of Work. "Entity Framework is a Repository" could lead to unnecessary confusion."

WebAPI ODATA -- Consuming With MVC Using Standard Controller/Ioc/Repository/UoW Sort of Architecture

Working with WebAPI ODATA services with javascript is not a problem... but what is a current recommendation to wrap the http calls (CRUD) to be consumed through a MVC5 application with a repository. Much of the guidance I see ultimately goes directly to the entity/dbcontext. I am looking for guidance which demonstrates the "drinking of your own Kool-Aid" and consuming the same ODATA (and it can be plain WebAPI, also) published externally to consumers of an application.
In my mind, I'm looking at this sort of flow:
AppController (site1:443)-->AppRepository-->OdataController (apiSite2:443)-->OdataRepository-->DataSource
The secondary concern is that I don't necessarily want direct access to a datasource by any consumer--especially posts without being vetted and I don't want all (any) of the logic in the controller. I might be overthinking something...
In order to extract the business logic from the controller I typically either push said logic down to domain objects whenever possible. If that isn't possible, then I'll create a class specifically designed to manage the logic in question, such as an interaction between two different objects.
If all else fails, then I'll have the interaction managed by a service. The classes might look something like the following:
public class SomeApiController : ApiController
{
public SomeApiController(ISomeApiService service)
{
this.Service = service;
}
private ISomeApiService Service { get; set; }
public IHttpActionResult SomeMethod(int someObjectId)
{
// service manages the logic and either defers to the object in question or resolves it through some specialized class
var result = this.Service.SomeMethod(someObjectId);
return this.OK(result);
}
}
public class SomeApiService : ISomeApiService
{
public SomeApiService(ISomeRepository repository)
{
this.Repository = repository;
}
private ISomeRepository Repository { get; set; }
}
... and so on.
The idea being that the layers have no dependencies upon one another which cannot be resolved through the IoC container of your choice and that the dependencies only go one way. That is to say SomeApiService has no dependency on SomeApiController and SomeApiRepository would have no dependency on SomeApiService.

MVC + WebApi architecture translations in database

For the application I'm currently developing using the .net MVC stack, and WebApi I need to put translations in the database.
My entities look something like this:
public class Article {
public int Id { get; set; }
TitleTranslatableId { get; set; }
[NotMapped]
TitleValue { get; set; }
}
So TitleTranslatableId is a reference to a table in my database.
The question I'm currently having is:
Where should I get the translation? I've considering the following options:
In my repository layer, so when I use _repo.ReadArticle(1) it also queries the translations table
Business layer
In my controller using a translations controller so: article.titleValue = translationsAPI(article.TitleTranslatableId)
As a derived attribute in my entity:
TitleValue { get { return translationsAPI(this.TitleTranslatableId); } }
I would prefer to use the third option but I'm not quite sure what is the best solution
I recommend doing this in your "BUSINESS LAYER".
You controller should instruct your service/business layer to do the translation for you. You could create a TranslationHelper class which could be used by your service.
Though still am not sure what your question is: You want to get the translation of the word using web api or save after translating a word sent to your web api ?

where to keep frequently used methods in MVC

I need to implement MVC architecture in my company, So can anyone suggest where to keep frequently used methods to call on all pages. Like:
states ddl, departments ddl also roles list and etc...
Please give me suggestions where to keep them in architecture.
Thanks
There are different solutions depending on the scale of your application. For small projects, you can simply create a set of classes in MVC application itself. Just create a Utils folder and a DropDownLists class and away you go. For simple stuff like this, I find it's acceptable to have static methods that return the data, lists, or enumerations you require.
Another option is to create an abstract MyControllerBase class that descends from Controller and put your cross-cutting concerns in there, perhaps as virtual methods or properties. Then all your actual controllers can descend from MyControllerBase.
For larger applications, or in situations where you might share these classes with other MVC applications, create a shared library such as MySolution.Utils and reference the library from all projects as required.
Yet another possibility for larger solutions is to use Dependency Injection to inject the requirements in at runtime. You might consider using something like Unity or Ninject for this task.
Example, as per your request (also in GitHub Gist)
// declare these in a shared library
public interface ILookupDataProvider
{
IEnumerable<string> States { get; }
}
public class LookupDataProvider: ILookupDataProvider
{
public IEnumerable<string> States
{
get
{
return new string[] { "A", "B", "C" };
}
}
}
// then inject the requirement in to your controller
// in this example, the [Dependency] attribute comes from Unity (other DI containers are available!)
public class MyController : Controller
{
[Dependency]
public ILookupDataProvider LookupDataProvider { get; set; }
public ActionResult Index()
{
var myModel = new MyModel
{
States = LookupDataProvider.States
};
return View(myModel);
}
}
In the code above, you'll need to configure your Dependency Injection technology but this is definitely outside the scope of the answer (check SO for help here). Once configured correctly, the concrete implementation of ILookupDataProvider will be injected in at runtime to provide the data.
One final solution I would suggest, albeit this would be very much overkill for small projects would be to host shared services in a WCF service layer. This allows parts of your application to be separated out in to highly-scalable services, should the need arise in the future.

Standard way to return JSON for view

I've got a view with a few simple fields and a jQuery grid. The fields I populate via my Model so my first thought was to try and populate my grid via the same way. The thing is that after banging my head against the problem for a bit I started to wonder if maybe I was trying to go against the grain to much. It seems like the generally accepted practice (and more importantly how things are designed) that components on the view which use json for their data work best when they can make a separate call to get a JSONResult returned which they will then process.
Normally this wouldn't be a big deal but for various future proofing reasons (not my decision.. the fun of having an architect) we've got a separate WCF layer that our MVC layer calls. So now I have to be worried about making too many granular calls. This is what actually lead me to try the model based population approach. What I'm wondering is how common this approach is or if everyone just has a bunch of controller methods for their UI components to call to get JSON?
I use a standard generic model for JSON results like
public class JSONOutputModel<T>{
public int RequestId{ get; set; }
public string Type { get{ return typeof(T).FullName; } }
public T Model{ get; set; }
}
Then I have standard generic send/receive JSON methods in JavaScript.
The most generic way you can return json from an action is to simply call the Json() method.
return Json(viewModel);
If you are specifically returning data for jqGrid, you could use your own ActionResult. Here is what we use. We also have an extension method to translate to this result from our service paging wrapper.
public class TableResult : ActionResult
{
public override void ExecuteResult(ControllerContext context)
{
context.HttpContext.Response.Write(ToJqGridJson());
}
public object ToJqGridJson()
{
return new {total = Total, page = Page, records = Records, rows = Rows};
}
public int Total { get; set; }
public int Records { get; set; }
public int Page { get; set; }
public object[] Rows { get; set; }
}
In the controller:
return new TableResult() { ... };
or
return queryResults.ToTableResult();
As far as future-proofing, don't even try! You're going to end up with a lot of big up front design and I guarantee it won't pay off. We learned the hard way and just recently started throwing out lots of our abstractions. There's no sense writing code if you don't know exactly how it's going to be used in the future. Besides, WCF can easily be replaced by an MVC app itself. MVC doesn't have to return just web sites. We have switched to using .net 4.0's javascript serializer + MVC + a client javascript deserializer to provide web services. You can share the authentication you already wrote for MVC, plus all your filters, etc and not have to worry about configuring the hideous mess of WCF. Look at where technology is moving towards: mobile and integrated! You aren't going to be doing WCF on your phone. Look at JSON, ATOM, RSS etc.
http://ayende.com/Blog/archive/2011/02/23/flatten-your-architecture-simplicity-as-a-core-value.aspx

Resources