MVC4 Quick Tip #2–Use Delegates to setup the Dependency Resolver instead of creating a Dependency Resolver class

by ely February 20, 2012 15:29

I’m a big fan of cutting out unneeded or unnecessary code, so here is a tip that isn’t new in MVC4, but I just discovered it and thought it was really cool and worth sharing.  When using IOC in MVC, you setup a class that implements IDependencyResolver, which has methods to return services for a given type.  While these classes where simple, it always seemed like a bit of ceremony was required whenever starting up a new MVC app.

The following example shows what a DependencyResolver class looks like using my favorite IOC framework, Ninject:

   1:  public class NinjectDependencyResolver : IDependencyResolver
   2:      {
   3:          private readonly IKernel _kernel;
   4:   
   5:          public NinjectDependencyResolver(IKernel kernel)
   6:          {
   7:              _kernel = kernel;
   8:          }
   9:   
  10:          public object GetService(Type serviceType)
  11:          {
  12:              return _kernel.TryGet(serviceType);
  13:          }
  14:   
  15:          public IEnumerable<object> GetServices(Type serviceType)
  16:          {
  17:              return _kernel.GetAll(serviceType);
  18:          }
  19:      }

Nothing terribly complicated, but a lot of fluff.

I saw in a demo in last week’s C4MVC talk, that the DependencyResolver that was setup to create the APIController classes had some overrides I never saw before, and low and behold, the standard MVC DependencyResolver also has these overrides:

ioc

So instead of providing the SetResolver method with a DependencyResolver class, you can just provide it two delegate methods that would normally be in the DependencyResolver (GetService, and GetServices):

   1:  DependencyResolver.SetResolver(
   2:                  x => kernel.TryGet(x),
   3:                  x => kernel.GetAll(x));

POW!  Cut that 20+ line class down to a method that takes two parameters.  BAM!

Tags:

mvc

MVC4 Quick Tip #1–Put your API Controllers in a different folder to avoid class naming collisions

by ely February 20, 2012 15:23

This post is the start of a series of quick tips for Asp.Net MVC 4, which was released in beta form last week.  You can find out more about MVC4 and download the beta from www.asp.net/mvc/mvc4.

Disclaimer: This code is based on MVC 4 Beta 1, and might change in future releases.

MVC 4 ships with the new Asp.net Web APIs, which allow you to create RESTful services from within your web projects (Web Forms or MVC).  In previous versions of MVC, people commonly used Controllers to return JSON to front end websites and other clients.  While this worked for many scenarios, it was difficult to create services that were truly RESTful in nature, taking advantage of all that HTTP had to offer.

With Web APIs, you can now create “API” Controllers.  While these controllers don’t require you to follow REST, their default behavior encourages you to do so.

When starting up a new MVC 4 project, you might be tempted to put new API Controllers in the same folder  (or more accurately, namespace) as your MVC Controllers.  While this will work, you are limited in that you cannot have two classes with the same name in the same namespace.  It will be a common scenario when you have a MVC Controller with the same name as a API Controller.  For instance, you can have a MVC AccountController to serve views for Accounts in your system, and an API AccountController to respond to XHR requests from your website (or mobile devices, other services, etc..).  One way I have found to get around this limitation is to put your API Controllers in a folder called API (or whatever folder/namespace you wish), like so:

controller

Default routes in MVC 4 will respond to MVC controllers with the route of /{controller},  and the default API route will respond to routes of /api/{controller}.  Since the AccountsController in the API folder inherits from APIController, it is okay that you have two classes named AccountsController in your project, the routing engine will know to use the correct one in the API folder.

Tags:

mvc

Global Filters and Dependency Injection in MVC3

by ely August 18, 2011 01:07

I’ve been struggling with finding a good solution to resolve dependencies in global filters lately.  Since it does not appear that global filters are created through the FilterAttributeFilterProvider (I don’t get any results back from base.GetFilters, hit me up if I’m doing something wrong here), my global filters that had resolve attributes on its properties were never being created by the provider, and thus, not getting those properties resolved.

It then dawned on me that the global filters are actually being instantiated in the global.asax.cs file (or wherever your app startup exists at).  So instead of newing up the object directly, I just let Ninject do it for me:

private static void RegisterGlobalFilters(GlobalFilterCollection filters, IKernel kernel)
        {
            filters.Add(new HandleErrorAttribute());
            filters.Add(kernel.TryGet(typeof(UserProviderFilterAttribute)));
        }

At first this felt like a giant hack, but after awhile I warmed up to it and realized that since this is the area of responsibility for creating global filters, that using Ninject to resolve its dependencies does in fact belong here.

If you have other methods for doing resolving your dependencies in global filters, or if I am way off base, I would love to hear any comments or suggestions.

Tags: ,

mvc

String Extension Methods in Razor

by ely January 08, 2011 17:16

The new Razor view engine contains several handy extension methods you can use in your views.  These methods mostly deal with either detecting if a string value can be converted to a particular type, or converting string values to a particular type.  For instance, the following code checks to see if a querystring value is a decimal, and if so, to format it as a currency:


@{
    if (Request.QueryString["amount"].IsDecimal())
    {
        @Request.QueryString["amount"].AsDecimal().ToString("c")W
    }
    else
    {
        @: Amount is not a valid number
    }
}

There are Is(Type), and As(Type) methods for bools, datetimes, decimals, floats, and ints. All of the As(Type) conversion methods take in an optional second parameter that can serve as the default value in case the conversion is not successful.

These extension methods are handy and can save some time and lines of code when dealing with strings.  They are in the System.Web.WebPages namespace, which new projects in MVC3 and Webmatrix automatically reference, so you do not need to worry about adding any using statements into your views in order to take advantage of them.  If you want to take advantage of them in your views, you can simply add a using statement to System.Web.WebPages.

Tags:

mvc | razor

Demo from my MVC/EF/jQuery Talk

by ely August 26, 2010 16:45

Sorry this is a few days late, but I have finally uploaded my demo from my talk at last Monday’s Denver Visual Studio.Net User Group

If you were there, thanks for coming out and seeing our community launch event for Visual Studio 2010.  We had a packed house of 100+ people, and had a great time.

In order to run this demo, you will need the Entity Framework Code First CTP4 binaries.  See Scott Guthrie’s post about EF4 code first and info on how to download it

Tags:

.Net | jQuery | VS2010 | mvc | entity framework

Powered by BlogEngine.NET 2.0.0.36
Theme by Mads Kristensen | Modified by Mooglegiant

About me

@ElyLucas

I am a Denver based software developer, focusing mainly on web technologies in the Microsoft stack.  I dig Asp.Net, MVC, jQuery, C#, JavaScript, and HTML5.  I am starting to dabble in mobile technologies like iOS, Android, and wp7, and have particular interests in mobile web.  I am a Microsoft MVP for Asp.Net/IIS.  I live in Westminster, CO with my wife, son, and dog.  During the day, I sling code for @aspenware creating awesome software.


Month List

Page List

Site hosted by: