Skip to content

Instantly share code, notes, and snippets.

@sslotsky
Last active August 29, 2015 14:27
Show Gist options
  • Save sslotsky/9dfa691d970d8f6927fa to your computer and use it in GitHub Desktop.
Save sslotsky/9dfa691d970d8f6927fa to your computer and use it in GitHub Desktop.
Services as controller properties in a Resource Oriented Architecture
public class ChatRoomsController : ResourceController<ChatRoom>
{
public ChatRoomsController() : base()
{
this.Service = new ChatRoomService(this.ConnectionString); // ConnectionString is inherited from a super class
}
public ActionResult Index()
{
var chatRooms = this.Service.FindAll(cr => cr.Active).Select(cr => new ChatRoomViewModel(cr));
return this.View(chatRooms);
}
}
public class ChatRoomService : Service<ChatRoom>
{
public ChatRoomService(string connectionString) : base(connectionString) { }
public override DbSet<ChatRoom> Relation(ChatDbContext context)
{
return context.ChatRooms;
}
}
public abstract class ResourceController<T> : BaseController
{
public Service<T> Service { get; private set; }
}
public abstract class Service<T>
{
public string ConnectionString { get; private set; }
public abstract DbSet<T> Relation(ChatDbContext context);
public Service(string connectionString)
{
this.ConnectionString = connectionString;
}
public List<T> FindAll(Func<T,bool> predicate)
{
List<T> results;
using (var context = new ChatDbContext(this.ConnectionString))
{
results = this.Relation(context).All(predicate).ToList();
}
return results;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment