I am used to developing with N-Tier architecture, i.e. Data Access Layer, Business Logic Layer, etc
Can anyone provide any advice or links about the best location for my business logic?
Do I put all of this into classes within the Models folder of my Silverlight application?
Paul
Business logic, as well as the data, is typically part of the Model layer in MVVM. The View is the visuals, and the ViewModel is the "glue" that lets you work with the business specific logic and data.
Anything that's specific to the domain or business should be reusable by other applications, using other architectures.
That's a good question, the answer will partly be a matter of the project's complexity and of developer's taste.
Some MVVM projects I have seen put everything in the VM part, so the View's .cs files are empty (because everyone knows 'code-behind' is evil </sarcasm>) and the Model files contain passive 'storage classes' (ie C structs with encapsulation basically).
It can be a decent choice for some simple projects (like a viewer with barely any logic). But it will lead to blob-like View Models trying to do everything, which is unmanageable, if your project has any complexity.
Reed Copsey's answer (business logic/data access should be decoupled of View/ViewModel) is the best solution for projects with any significant complexity.
I faced the same problem and decided to go this way:
I created classes like controllers in MVC (performing some actions with my model) and I work with them in all ViewModels.
For example: our application has a list of books. We need to add/edit/delete them.
So we have a model:
public class Book
{
public int BookId { get; set; }
public string Title { get; set; }
public string Author { get; set; }
}
Then we have a controller class:
public class BookController
{
string dbPath = ...;
public void AddBook(string title, string author)
{
var book = new Book() { Title = title, Author = author };
AddBook(book);
}
public void DeleteBook(int id)
{
using (var db = new SQLiteConnection(dbPath))
{
db.Delete<Book>(id);
}
}
public void DeleteBook(Book book)
{
using (var db = new SQLiteConnection(dbPath))
{
DeleteBook(book.BookId);
}
}
public List<Book> GetAllBooks()
{
using (var db = new SQLiteConnection(dbPath))
{
return db.Table<Book>().ToList();
}
}
public Book FindBook(string title, string author, int id)
{
.....
}
}
Now we can use it wherever we need, e.g.:
public class BookListViewModel : ViewModelBase
{
public BookListViewModel()
{
GetData();
}
private void GetData()
{
BookController bc = new BookController(); // here we start using our controller.
_books = new List<Book>();
_books = bc.GetAllBooks();
}
}
Such approach helps us:
- keep all business logic separately (in controller class)
- avoid code duplication