Last active
August 29, 2015 14:27
-
-
Save sslotsky/9dfa691d970d8f6927fa to your computer and use it in GitHub Desktop.
Services as controller properties in a Resource Oriented Architecture
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ChatRoomService : Service<ChatRoom> | |
{ | |
public ChatRoomService(string connectionString) : base(connectionString) { } | |
public override DbSet<ChatRoom> Relation(ChatDbContext context) | |
{ | |
return context.ChatRooms; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public abstract class ResourceController<T> : BaseController | |
{ | |
public Service<T> Service { get; private set; } | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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