Recently I have designed an architecture which supports the MVC pattern over the ASP.NET platform for an existing application.
It is well known that new ASP.NET MVC Framework is the best option to implement the MVC pattern, but it is also true that is difficult to adapt existing applications to this framework. So, I have designed an alternative and very simple solution in order to reach the same goal: MVC over ASP.NET.
In the architecture designed, every View implements an interface which acts as contract between the View and the Controller. This interface exposes the events and methods of the View.
internal interface ICustomersView
{
event EventHandler<GenericEventArgs<string>> FindCustomer;
void FillCustomers(IList<Customer> customers);
}
The Controller has to attach itself to the events and call to the methods of the View Interface.
internal class CustomersController : ControllerBase<ICustomerView>
{
public CustomersController(ICustomersView view) : base(view)
{
view.FindCustomers += new EventHandler<GenericEventArgs<string>>(view_FindCustomers);
}
private void view_FindCustomers(object sender, GenericEventArgs e)
{
IList<Customer>
View.FillCustomers(customers);
}
private IList<Customer>
{
// Use the model in order to find customers
}
As you can see, the Controller receives the interface of the View and it doesn't know nothing about the View Implementation, so you can test the Controller using a mocked View.
Then, you need to create the ASP.NET WebForm that implements the ICustomerView interface.
public partial class CustomersView :
ViewBase<CustomersController, ICustomersView>, ICustomerView
{
public event EventHandler<GenericEventArgs<string>> FindCustomers;
public void FillCustomers(IList<Customer> customers)
{
customersGrid.DataSource = customers;
customersGrid.DataBind();
}
protected void OnFindCustomers(GenericEventArgs<string> args)
{
if(FindCustomers != null)
{
FindCustomer(this, args)
}
}
protected void btnSearch_Click(object sender, EventArgs e)
{
OnFindCustomer(new GenericEventArgs<string>(txtSearch.Text));
}
}
Finally, the classes that you need to implement this architecture are the following:
internal abstract partial class ViewBase<TController, TViewInterface>:
Page
where TViewInterface : class
{
public ViewBase()
{
Type controllerType = typeof(TController);
Activator.CreateInstance(controllerType, this as TViewInterface);
}
}
internal abstract class ControllerBase<TViewInteface>
where TViewInteface : class
{
public TViewInteface View { set; get; }
public ControllerBase(TViewInteface view)
{
View = view;
}
}
internal class GenericEventArgs<TArgument> : System.EventArgs
{
public GenericEventArgs()
{
}
public GenericEventArgs(TArgument argument)
{
Argument = argument;
}
public TArgument Argument { get; set; }
}
0 comments:
Post a Comment