Dependency in MVC2

Idea from this post.
By default, MVC2 can’t handle ctor injection.

    [HandleError]
    public class HomeController : Controller
    {
        private readonly IGreatingService _greatingService;

        public HomeController(IGreatingService greatingService)
        {
            _greatingService = greatingService;
        }

        public ActionResult Index()
        {
            ViewData["Message"] = "Welcome to ASP.NET MVC!" + _greatingService.SayHello();

            return View();
        }
}

Solution: A custom ControllerFactroy can be set in App_start.


protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            RegisterRoutes(RouteTable.Routes);

            ControllerBuilder.Current.SetControllerFactory(IoC.GetControllerFactory());
        }

   public static class IoC
    {
        public static IKernel Kernel;

        static IoC()
        {
//            ObjectFactory.Initialize(x => x.AddRegistry(new ControllerDependencyRegistry()));
            Kernel = new StandardKernel(new ControllerModule());
        }

        public static IControllerFactory GetControllerFactory()
        {
            return new ControllerFactory();
        }

        public static object Get(Type type)
        {
//            return ObjectFactory.GetInstance(type);
            return Kernel.Get(type);
        }
    }

    public class ControllerFactory : DefaultControllerFactory
    {
        protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
        {
            if (controllerType == null)
            {
                return base.GetControllerInstance(requestContext, controllerType);
            }

            return IoC.Get(controllerType) as Controller;
        }
    }

    //  Ninject implementation
    public class ControllerModule : NinjectModule
    {
        public override void Load()
        {
            Bind<IGreatingService>().To<GreatingService>();
        }
    }

    // StructureMap implementation
    public class ControllerDependencyRegistry : Registry
    {
        public ControllerDependencyRegistry()
        {
            For<IGreatingService>().Use<GreatingService>();
        }
    }
Advertisements

ASP.net Dynamic Data

David Ebbo’s screen cast is very good for show off the new ASP.net Dynamic Data. No wonder this technique alone will become one of the three major MS web solutions. It’s based on Linq to Sql, and very similar to MVC, or MV without C, because it’s still using webForms with many prebuild view templates. The folder structures are same as rails, each module should name after it’s table/model.

The dynamic field is very handy, I like RenderHint, only concern is it’s build on MS Ajax toolkit which is replaced by JQuery now.

Experiencing ASP.NET MVC – Day 1

  1. Install
    I installed ASPNet Extension Preview before VS2008, so when I opened up VS2008, I didn’t see new project type named with ‘ASP.NET 3.5 MVC Web Application’. Had to re-install to make those new items appear.
    Entity Framework is also needed, don’t know why.
  2. Linq
    Following ScottGu’s instructions Part 1, used a Linq to ADO to SQL class. IT IS REALLY COOL! I like the graphic view of dbml file. Looked into the source, it works like a wrapper for ActiveRecord, and the most important thing is, it can support stored procedure so easily.
  3. MS Unit Test
    The default MVC web application comes with a test project using ‘Microsoft.VisualStudio.TestTools.UnitTesting’, ScottGu didn’t give his implementation of TestViewEngine which many people are asking for.
    Fortunately, I found an example of TestViewEngine from JAK’s blog whose idea is from Phil Haack’s Rhino mock solution.
    I could not make Haack’s test code work in MSUnitTest, so I commented out mocks.VerifyAll, and added assert code after. All the test case turned to green then. Woohoo!
  4. ActionLink
    This is pretty similar to robyOnrails, but I was having problem to make this happen

    <%= Html.ActionLink(c.CategoryName, new { action=”List”, category =c.CategoryName}) %>

    unless I changed category to id, also, the controller action list(string category) needs to change to List(int id).
    I don’t know how could Scott change this default id parameter to customized category, until I run into SocttGu’s blog part 2, URL routing. By adding

                RouteTable.Routes.Add(new Route
    {
    Url = “Products/List/[category]”,
    Defaults = new { controller = “Products”, action = “List”, category = (string)null },
    RouteHandler = typeof(MvcRouteHandler)
    });

    in front of default routing:

                RouteTable.Routes.Add(new Route
    {
    Url = “[controller]/[action]/[id]”,
    Defaults = new { action = “Index”, id = (string)null },
    RouteHandler = typeof(MvcRouteHandler)
    });

    Everything works just good as ScottGu’s example.

 



Way To MVP: MVC vs. MVP

As Darron Schall said,

Instead of a Controller, we now have a Presenter, but the basic idea remains the same – the model stores the data, the view is a representation of that data (not necessarily graphical), and the presenter coordinates the application.

Additionally, the View in MVP is responsible for handling the UI events (like mouseDown, keyDown, etc), which used to be the Controllers job, and the Model becomes strictly a Domain Model.

My thoughts: Presenter acts as a controller in MVC, kind of, but it’s loosely coupled to View. View can switch Presenter by coding. The UI can have multiple views to implement multiple presenters. In fact, it’s common each presenter is created to have its unique purpose which can make test easier, e.g. AddCustomerPresenter.cs, IEditCustomerView.cs and IListCustomersView.cs.

Both Presenter and Model can have methods, so does View. (In ROR, view is very static.) Apparently presenter is a connection between View and Model. RoR doesn’t have this middle layer.

Billy McCafferty ‘s article is good for dotnet dummies, I was very easy to follow. JP’s level is too high for me, currently.

n-tier in dotNet

Server side or component programming in dotnet is more complicated than in PB/EAServer, lots of concerns, such as life cycle management, reliability, state management, scalability, and security… I have already started to miss Jaguar manager. What a nice admin tool!

For web app, there are many options, say MonRail, but developers won’t get webform’s drog-drop features in vm views. Almost the same problem about pb datawindow.

Yes, asp.net is not a true MVC, but,

Yes, even MS does not claim ASPX as a true MVC. They would like it to be called as MVP (Model View Presenter). Actually view & controller are tightly coupled in ASPX. This violates the original concept of MVC preached & shipped by JAVA/STRUTS world. But MS answer is that in most of the deployment scenarios the controller happens to be tied to a framework/technology and cannot be generic enough. Mean to say that a controller written for web application cannot be used in another client server application context. Also they claim that writing generic controller would lead to the introduction of more layers in the request processing and could be a real killer in some situations. — girish,  a dotnet expert

For desktop app, rich client or thick client, distribute seems to be the only way to implement MVC, MVP?

DotNet Remoting is old fashion, WCF is 20-30% faster but is also too new:

WCF is part of .NET 3.0 and requires .NET 2.0, so it can only run on operation systems that support it. Presently this list consists of Windows Vista (client and server), Windows XP SP2, and Windows Server 2003 SP1 or their later versions.