Shannon Deminick's blog all about web development

Introducing ‘Smidge’ – an ASP.NET 5 runtime JS/CSS pre-processor

December 11, 2014 23:19

During the past month I decided to dive deep into learning ASP.NET 5, and what better way to learn than to start a new OSS project :)

I chose to make a new new simple and extensible Javascript/CSS runtime pre-processor for ASP.NET 5. It does file minification, combination and compression, has a nice file caching layer and it’s all done in async operations. I ported over a few ideas and code snippets from CDF (client dependency framework) but with a more modern approach. I’ve called it ‘Smidge’ = something really small.

The project is on GitHub, it’s still a work in progress but its functional and there’s even some documentation! In the next few weeks I’ll get more of the code and docs updated and hopefully have a beta release out. In the meantime, you can clone the source, browse the code, build it and of course use it if you like.

Project details

It’s currently only targeting aspnet50 and not the Core CLR… I didn’t start with Core CLR because there was some legacy code I had to port over and I wanted to get something up and working relatively quickly. It shouldn’t be too much work to convert to Core CLR and Mono, hopefully I’ll find time to do that soon. It’s referencing all of the beta-* libraries from the ASP.NET 5 nightly myget feeds since there’s some code I’m using that isn’t available in the current beta1 release (like Microsoft.AspNet.WebUtilities.UriHelper). The target KRE version is currently KRE-CLR-amd64 1.0.0-beta2-10760.


I’ve put up an Alpha 1 release on Nuget, so you can install it from there:

PM> Install-Package Smidge -Pre

There’s some installation instructions here, you’ll need to add the smidge.json file yourself for now, can’t figure out how to get VS 2015 (kpm pack) to package that up … more learning required!


There’s certainly a lot of detective work involved in learning ASP.NET 5 but with the code being open source and browse-able/searchable on GitHub, it makes finding what you need fairly easy.

Model binding with FromServices in ASP.Net 5

December 8, 2014 03:34

Here’s a new nifty feature I found in ASP.Net 5 – you can construct your model during model binding with IoC without any additional work. This is available on the dev branch on GitHub and is based on something called ServicesModelBinder. This is actually pretty cool because it means that you can have a model wired up with all of it’s dependencies based on IoC and then bound to your controller action’s parameters.

FromServices attribute

There’s a new attribute called FromServices which is what you use to enable this functionality. For example:

public async Task<ActionResult> GetProduct(
    [FromServices]ProductModel product)


What this attribute does is tell MVC to bind the model using IServiceActivatorBinderMetadata which is what the FromServices attribute implements. This in turn tells MVC to lookup the model binder that is aware of IServiceActivatorBinderMetadata which happens to be the ServicesModelBinder.


This model binder is pretty simple, it’s just going to resolve the model type from your IoC container. That could be pretty useful if you need to build up your model properties based on other services. I think some people might argue that this isn’t great practice because this is putting the binding logic in to the model itself instead of using a separate class to perform the binding logic. I suppose it’s up to the individual developer as to what their preference is. You can of course still create your own IModelBinder and use the ModelBinderAttribute to keep the model binding logic in the binder itself.

Incoming route values

Since the model is being created from IoC, how do you get the current route values to build up your model? To do that you’d put a constructor dependency on IContextAccessor<ActionContext>. This will give you all of the current route values, HttpContext, etc… basically everything you’d need to pull the data out of the current request to build your model.


Given the above GetProduct example, the ProductModel class could look like:

public class ProductModel
    public ProductModel(IContextAccessor<ActionContext> action, IProductService prodService)
        //TODO: Do some error checking...
        var productId = action.Value.RouteData.Values["product"];
        Value = prodService.Get(productId);

    public IProduct Value { get; private set; }

This is pretty simple – the IProduct is looked up from the IProductService based on the incoming ‘product’ route value. Then in the controller you could just do: product.Value to get the value for IProduct.

You then need to ensure that both IProductService and ProductModel are registered as services in your container and it’s really important that the ProductModel is registered as a Transient object

ASP.Net 5 Re-learning a few things (part 2)

November 21, 2014 01:34

This is part 2 of a series of posts about some fundamental changes in ASP.Net 5 that we’ll need to re-learn (or un-learn!)

Part 1: http://shazwazza.com/post/aspnet-5-re-learning-a-few-things-part-1/


This probably isn’t new news to most people since it’s really one of the fundamental shifts for ASP.Net 5 – There won’t be a System.Web DLL. Everything that you’ll install in your website will come as different, smaller, separate libraries. For example, if you want to serve static files, you’d reference the Microsoft.AspNet.StaticFiles package, if you want to use MVC, you’d include the Microsoft.AspNet.Mvc package.

ASP.Net 5: “consists of modular components with minimal overhead, so you retain flexibility while constructing your solutions

Web Forms

Gone! YAY! :-)

Web Forms will still be a part of .Net as part of the main framework in System.Web, just not part of ASP.Net 5.


An HttpModule simply doesn’t exist in Asp.Net 5, but of course there is a new/better way to achieve this functionality, it’s called Middleware. In an HttpModule, you had to execute code based on the various stages of a request, things such as AuthenticateRequest, AuthorizeRequest, PostResolveRequestCache, and other slightly confusingly named events. This is no longer the case with Middleware, things just make sense now … everything is simply a linear execution of your code. You can have multiple middleware’s defined to execute in your application and each one is registered explicitly in your Startup.cs file. As a developer, you are in full control of what get’s executed and in what order instead of not knowing which HttpModules are executing and not really in control of their order of execution. Middleware can simply modify a request and continue calling the next one in the chain, or it can just terminate the pipeline and return a result.

There’s loads of examples in the source for middleware, ranging from the static file middleware to cookie authentication middleware,  etc…

And here’s a good article that explains middeware registration and the flow of control.


HttpHandlers are also a thing of the past. All they really were was a request handler that was based on a specific request path. MVC (which now also includes WebApi) has got this covered. If you really wanted, you could create middleware for this type of functionality as well but unless you require something extraordinarily complex that MVC cannot do (and it can do a lot!), I’d recommend just sticking with MVC.

ASP.Net 5 - Re-learning a few things (part 1)

November 14, 2014 03:20

ASP.Net 5 (aka vNext) is now in Beta and the Visual Studio 2015 preview is now out! So, what is this new ASP.Net? The 2 biggest features is that it’s totally open source and it will support a cross platform runtime = great!! But it’s worth knowing that this is more or less a rebuild of ASP.Net and there’s quite a few things that we’ve become accustomed to that will now be totally different.

Configuration files

You know all of that junk in the web.config and perhaps in a bunch of other *.config files? Well that is gone! I think this is wonderful news because creating those configuration sections was a huge pain. Even better news is how easy creating custom configuration inputs will be in  ASP.Net 5 using the new IConfiguration and ConfigurationModel sources. OOTB Microsoft is releasing support for JSON, XML and INI files for configuration but of course you can easily create your own.  The repository for the configuration bits is here and a nice tutorial can be found here.

So what about configuration transforms?? That is also a thing of the past. In ASP.Net 5, “configuration” will mostly be done with code found in your Startup.cs file, anything that you want to enable in your application is done in this class. Any package that is installed in your app, you will need to opt-in to use it in your Startup.cs file. In some cases however, a configuration file might need to be updated/transformed… this could be due to an upgrade of a package. The good news is that the configuration sources in ASP.Net 5 are writable (IConfigurationSource) which means during startup or first access to your config, you could detect what needs to be updated to support your new version, make the updates in code and commit (ICommitableConfigurationSource) the changes.

Wait… isn’t that going to restart the app domain?? 

NOTE: If you are using IIS, there can still be a web.config which can be used to configure IIS settings under the system.webserver section.

AppDomain restarts

This is something that we’ve all become familiar with… you want to restart your app, just bump/touch the web.config and your app domain is restarted. This is something we’ll all have to un-learn. In ASP.Net 5 auto app domain restarts don’t happen. First, there is no web.config (or global.asax for that matter) so there are no files to bump/touch. Next, a big reason why auto app domain restarts can’t occur is because ASP.Net 5 will be able to be run on various different web servers which don’t really know about what it means to restart an app domain. For example if you’ve been playing around with vNext before you had a chance to use VS 2015, you might be familiar with the command line “k web” (see docs for details). This command will start up a simple web server: Microsoft.AspNet.Server.WebListener which will serve web requests. In order for app domain restarts to occur, it would need to know how to restart itself after it’s been shutdown which isn’t exactly possible with a simple command line process. Instead if you made any changes to your code and wanted to restart your app, you’d kill the process (ctrl + c) and just call k web again. Another thing to be aware of is that when you kill a process like this, your app domain does not gracefully shutdown/unwind, it’s simply terminated.

But not to worry! If you have a web app that requires restarting (i.e. maybe it installs plugins, etc…) and needs to gracefully unwind, it’s still possible and actually much more pleasant since you’ll be in full control of how/when it happens. In order for this to work you’ll need to be running a web server that knows how to start itself back up again - like IIS! The way to gracefully shutdown your app domain is by using: IApplicationShutdown when you want to gracefully shutdown your app. You could even use that in combination with an IFileWatcher and your own configuration files … if you really wanted to mimic an app domain restart by bumping/touching a file.

Deployments, bin folder and App_Code

Speaking of app domain restarts, how will ASP.Net 5 work when I put a new assembly in the /bin folder or add a new class to App_Code?? These are a couple more things that need to be un-learned. There really isn’t a /bin folder anymore (well, there is but it only contains one very special assembly if you are running IIS) and there isn’t any App_Code folder.  So where does all of this go?

When you publish a web project in VS 2015 (which uses kpm pack) you end up with a very different looking deployment structure. There’s two folder: approot and wwwroot.

wwwroot – is the content of your website, nothing more. Even things like configuration files don’t exist here, it’s just content that your webserver can serve.

approot – this is the brains of your website. It includes all of the binaries, config files, source code, etc… that is used to run your website.

Here’s a blog post that describes the deployed file structure 

Did you say source code?? Yup! By default kpm pack will deploy your site with all of it’s packages and the source code for all of your projects. The Roslyn compiler will take care of everything for you when your site needs to start serving requests. You can of course opt-out of this and have your site deployed as a compiled package.

Did you say Package?? Yup, as in Nuget package! Instead of a /bin folder full of assemblies, all of your dependencies will actually be Nuget references and stored in approot/packages and if you choose to deploy your website without source, it will be compiled into a Nuget package and deployed in the packages folder as well.

More to come….

So there’s a a few of the things that are pretty different in ASP.Net 5, there’s still more to come and hopefully I’ll find some time to write them all up!

Multiple WebApi controllers with the same name but different namespaces

June 27, 2014 05:56

Warren recently reported this issue on Umbraco which prohibits WebApi from routing to two different paths that specify the same controller name but different namespaces. This type of thing is fully supported in MVC but not in WebApi for some reason.

Here’s a quick example, suppose we have two controllers:

namespace Test1
    public class ConfigController : UmbracoApiController
        public int GetStuff()
            return 9876;
namespace Test2
    public class ConfigController : UmbracoApiController
        public int GetStuff()
            return 1234;

These controller definitions will create routes to the following paths respectively:

  • /umbraco/backoffice/test1/config/getstuff
  • /umbraco/backoffice/test2/config/getstuff

When these routes are created, the “Namespaces” data token is specified on the route, just like what is done in MVC, however in WebApi that needs to be done manually. Example:

var r = routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
r.DataTokens["Namespaces"] = new string[] {"Foo"};

but if you navigate to either of these paths you’ll end up with a message like:

Multiple types were found that match the controller named 'Config'. This can happen if the route that services this request ('umbraco/backoffice/Test2/Config/{action}/{id}') found multiple controllers defined with the same name but differing namespaces, which is not supported. The request for 'Config' has found the following matching controllers: Test1.ConfigController Test2.ConfigController

Custom IHttpControllerSelector

To achieve what we want, we need to create a custom IHttpControllerSelector. I’ve created this in the Umbraco core to solve the issue and the source can be found HERE. The implementation is pretty straight forward – it relies on the default WebApi controller selector for everything unless a “Namespaces” data token is detected in the route and more than one controller type was found for the current controller name in the app domain.

There’s some posts out there that elude to the possibility of this being supported in WebApi in the future but as of the latest source code for the DefaultHttpControllerSelector, it appears that the functionality is not yet there.

If you need this functionality though, this implementation is working and pretty simple. To register this selector just use this code on startup:

    new NamespaceHttpControllerSelector(GlobalConfiguration.Configuration));

Custom MVC routes within the Umbraco pipeline

May 24, 2014 02:03

A while ago I wrote a post on how to do custom MVC routing in Umbraco, though the end result wasn’t quite ideal. There were a few tricks required and It wasn’t perfect since there were problems with rendering macros on the resulting view, etc… This was due to not having a PublishedContentRequest object assigned to the context. So then we went ahead and created a new attribute to assign to your MVC action to resolve this: [EnsurePublishedContentRequestAttribute]

Like the last post, you can read a lot about all of this in this Our thread. With the [EnsurePublishedContentRequestAttribute] attribute you could now assign any IPublishedContent instance to a PublishedContentRequest and be sure that it was assigned to the UmbracoContext. But this still isn’t the most ideal way to go about specifying MVC routes to work within the Umbraco pipeline… so I’ve created the following implementation which works quite well.


A little bit of background in to custom MVC routes and Umbraco… The reason why it is not terribly straight forward to create a custom route and have it assigned to an Umbraco node is because the node doesn’t exist at your custom route’s location.

For example, if we have this route:

//Create a custom route
            controller = "MyProduct", 
            action = "Product", 
            sku = UrlParameter.Optional

Umbraco by default would have no idea what node (IPublishedContent) would be assigned to this. The way Umbraco relates a URL to an IPublishedContent instance is by a list of IContentFinder’s. A very easy way to relate a custom URL to an IPublishedContent instance is to create your own IContentFinder. Combine that with route hijacking and in many cases this would probably be enough for your custom routing needs. However, it does not solve how you would wire up custom route parameters to your controller like how MVC normally works. Like in the above routing example, you’d want to have the ‘sku’ parameter value wired up to your Action parameter.

The above route can work and be integrated into Umbraco by following some aspects of my previous blog post and use the [EnsurePublishedContentRequestAttribute], but we can make it easier…

Creating routes

The simplest way to demonstrate this new way to create MVC routes in Umbraco is to just show you an example, so here it is:

//custom route
        controller = "MyProduct",
        sku = UrlParameter.Optional
    new ProductsRouteHandler(_productsNodeId));

This is using a new extension method: MapUmbracoRoute which takes in the normal routing parameters (you can also include constraints, namespaces, etc….) but also takes in an instance of UmbracoVirtualNodeRouteHandler.

The instance of UmbracoVirtualNodeRouteHandler is responsible for associating an IPublishedContent with this route. It has one abstract method which must be implemented:

IPublishedContent FindContent(RequestContext requestContext, UmbracoContext umbracoContext)

It has another virtual method that can be overridden which will allow you to manipulate the PublishedContentRequest however you’d like:

PreparePublishedContentRequest(PublishedContentRequest publishedContentRequest)

So how do you find content to associate with the route? Well that’s up to you, one way (as seen above) would be to specify a node Id. In the example my ProductsRouteHandler is inheriting from UmbracoVirtualNodeByIdRouteHandler which has an abstract method:

IPublishedContent FindContent(RequestContext requestContext, UmbracoContext umbracoContext, 
    IPublishedContent baseContent);

So based on all this information provided in these methods, you can associate whatever IPublishedContent item you want to the request.

Virtual content

This implementation expects any instance of IPublishedContent, so this means you can create your own virtual nodes with any custom properties you want. Generally speaking you’ll probably have a real Umbraco IPublishedContent instance as a reference point, so you could create your own virtual IPublishedContent item based on PublishedContentWrapped, pass in this real node and then just override whatever properties you want, like the page Name, etc..

Whatever instance of IPublishedContent returned here will be converted to a RenderModel for use in your controllers.


Controllers are straight forward and work like any other routed controller except that the Action will have an instance of RenderModel mapped to it’s parameter. Example:

public class MyProductController : RenderMvcController
    public ActionResult Product(RenderModel model, string sku)
        //in my case, the IPublishedContent attached to this
        // model will be my products node in Umbraco which i 
        // can now use to traverse to display the product list
        // or lookup the product by sku
        if (string.IsNullOrEmpty(sku))
            //render the products list if no sku
            return RenderProductsList(model);
            return RenderProduct(model, sku);

I have this all working well in a side project of mine at the moment. This functionality will be exposed in an upcoming Umbraco version near you  :)

It’s also worth noting that all of this was accomplished outside of the Umbraco core with the publicly available APIs that currently exist. I will admit though there were a few hacks involved which of course won’t be hacks when moved into the core ;)

Multi targeting a single .Net project to build for different framework versions

May 2, 2014 04:18

Consider this scenario:

  • I have a project that relies on ASP.Net MVC and currently this project is built against the .Net framework 4.0 and MVC 4
  • I want to support MVC 5 for this project
  • To support MVC 5, I’d need to upgrade the project to use .Net framework 4.5
  • This would mean that developers still running .Net framework 4.0 would no longer be able to use my updated project

I also don’t want to have to create different projects and assemblies that target specific MVC versions (in this case you’d end up with assembly names like MyProject.MVC4.dll and MyProject.MVC5.dll). I have seen this done with other solutions and it works but I feel it is not necessary unless your project is using specific functionality from a particular MVC version.

In my case my project will compile perfectly against MVC 4 and 5 without any codebase changes so I’m not actually targeting against a specific MVC version ( >= 4 ). If your project uses specific functionality from the different MVC versions I think you will have to output different assemblies like MyProject.MVC5.dll. In that case this post will probably help: http://blogs.korzh.com/2013/12/nuget-package-different-mvc-versions.html

The goal

The end result is that I want a single project file that has 4 build configurations:

  • Debug / Release
    • These will build against .Net 4.0
    • This will reference MVC 4
  • Debug-Net45 / Release-Net45
    • This will build against .Net 4.5
    • This will reference MVC 5

Each of these build configurations exports the same assembly name: MyProject.dll

I then want a single NuGet package which will install the correct DLL based on the .Net version that the user has installed.

How it’s done

Build configuration setup

To start with you’ll have a project that targets .Net framework 4.0 and references MVC 4 and 2 standard build configurations: Debug, Release.

First we need to create 2 new build configurations: Debug-Net45 and Release-Net45 and have these configurations output the DLLs to a custom folder. To do this we launch the Configuration Manager:


Create a new build configuration:


Enter the name of the new configuration and copy the configuration from it’s associated existing one. So Debug-Net45 would copy from Debug and Release-Net45 copies from Release.


Do this for both configurations – Debug-Net45 and Release-Net45.

Project setup

The next step requires manually editing your .csproj file since Visual Studio doesn’t want to normally allow you to do this. This is how you can configure each build type to target a different framework version. You’ll first need to find these 2 entries:

<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">

Inside each of these elements you need to explicitly tell these build configurations to use .Net framework 4.0 by adding this element:


Next you’ll want to copy/paste both of these property groups and:

  • Change the Condition to check for the new build configurations and to target .Net framework 4.5
  • Change the OutputPath to have a specific .Net 4.5 folder
  • Change the TargetFrameworkVersion to be .Net 4.5

You should end up with 2 new elements that look something like:

<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug-Net45|AnyCPU'">
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release-Net45|AnyCPU'">

Next we need to do this for the MVC references or any framework specific references you need to target. In this example it is just the MVC references and you’ll need to wrap them with an ItemGroup element, you’ll end up with something like this to target the MVC 4 libs:

<ItemGroup Condition=" '$(Configuration)'=='Debug' Or '$(Configuration)'=='Release'">
    <Reference Include="System.Web.Helpers, Version=, .....">
    <Reference Include="System.Web.Mvc, Version=, .....">
    <Reference Include="System.Web.Razor, Version=, .....">
    <Reference Include="System.Web.WebPages, Version=, .....">
    <Reference Include="System.Web.WebPages.Deployment, Version=, .....">
    <Reference Include="System.Web.WebPages.Razor, Version=, .....">

Then we need to go ahead and copy/paste this block but target the different build configurations and then swap out these MVC 4 version references with the MVC 5 version references.

Nuget package restore

For this tutorial I’m assuming you are using Nuget to reference your MVC libs and an easy way to get Nuget to play reasonably with this setup is to enable Nuget package restore for your solution – right click on your solution and click the button:


Then in your packages.config file you can manually add the MVC 5 references:

<?xml version="1.0" encoding="utf-8"?>
  <package id="Microsoft.AspNet.Mvc" 
           version="4.0.30506.0" targetFramework="net40" />
  <package id="Microsoft.AspNet.Razor" 
           version="2.0.30506.0" targetFramework="net40" />
  <package id="Microsoft.AspNet.WebPages" 
           version="2.0.30506.0" targetFramework="net40" />
  <package id="Microsoft.Web.Infrastructure" 
           version="" targetFramework="net40" />
  <package id="Microsoft.AspNet.Mvc" 
           version="5.0.0" targetFramework="net45" />
  <package id="Microsoft.AspNet.Razor" 
           version="3.0.0" targetFramework="net45" />
  <package id="Microsoft.AspNet.WebPages" 
           version="3.0.0" targetFramework="net45" />

Now when you build your solution under the different build configurations Nuget will automatically go and get the correct MVC versions based on the current .Net Framework version.

Thats it!

With all of this in place it should ‘just work’ :) You will notice some odd looking icons in your references list in Visual Studio but it’s nothing to worry about, Visual Studio is just confused because it isn’t familiar with how you’ve tricked it!


So now when you build using your different build configurations, it will output the correct DLLs to the correct build folders:

  • Both Debug & Release will output to /bin/Debug & bin/Release with MVC 4 libraries and the MyProject.dll will be compiled against .Net Framework 4.0
  • Both Debug-Net45 & Release-Net45 will be output to /bin/Debug-Net45 & /bin/Release-Net45 with MVC 5 libraries and the MyProject.dll will be compiled against .Net Framework 4.5

And here’s some proof:



If you are using some automated build processes with MSBuild you can then just target the build configuration names you’d like to export.

The Nuget setup is pretty simple since you can target your dependencies by framework:

<group targetFramework="net40">
<!--between 4 and less than version 5-->
<dependency id="Microsoft.AspNet.Mvc" version="(4.0.20710,5)" />

<group targetFramework="net45">
<!--between 4 and less than version 6 (who knows what'll happen then)-->
<dependency id="Microsoft.AspNet.Mvc" version="(4.0.20710,6)" />

Then for each of your lib files in Nuget you ensure that you output them to the framework specific /lib folders such as:


This process has been implemented for the Client Dependency Framework version 1.8.0 to support MVC 4 and 5 without having to change the assembly name.

WebApi per controller configuration

March 21, 2014 00:56

This is more of a blog post about what not to do :)

At first glance, it would seem relatively painless to change your WebApi controller’s configuration, I’d assume most people would do what I initially did. Say for example you wanted to have your controller only support JSON, here’s what I initially tried (DO NOT DO THIS):

protected override void Initialize(HttpControllerContext controllerContext)
    var toRemove = controllerContext.Configuration.Formatters
        .Where(t => (t is JsonMediaTypeFormatter) == false).ToList();
    foreach (var r in toRemove)

Simple right, just override initialize in your controller and change the current controllerContext’s configuration…. WRONG :(

What this is actually doing is modifying the global WebApi configuration though it’s not clear that this is the case. Unfortunately the actual Configuration property on the controllerContext instance is assigned to the global one. I’m assuming the WebApi team has done this for a reason but I’m not sure what that is; as seen above it’s very easy to change the global WebApi configuration at runtime. Seems to me like it might have been a better idea to clone the global configuration instance and assign that to each HttpControllerContext object.

The correct way to specify per controller custom configuration in WebApi is to use the IControllerConfiguration interface. You can read all about here and it is fairly simple but it does seem like you have to jump through a few hoops for something that initially seems very straight forward.

Razor + dynamic + internal + interface & the 'object' does not contain a definition for 'xxxx' exception

April 11, 2013 16:49

I’ve come across this strange issue and decided to blog about it since I can’t figure out exactly why this is happening it is clearly something to do with the DLR and interfaces.

First, if you are getting the exception: 'object' does not contain a definition for 'xxxx' it is related to either an object you have being marked internal or you are are using an anonymous object type for your model (which .Net will always mark as internal).

Here’s a really easy way to replicate this:

1. Create an internal model

internal class MyModel
public string Name {get;set;}

2. Return this model in your MVC action

public ActionResult Index()
return View(new InternalTestModel("Shannon"));

3. Make your view have a dynamic model and then try to render the model’s property

@model dynamic

You’ll get the exception:

Server Error in '/' Application.

'object' does not contain a definition for 'Name'

So even though the error is not very informative, it makes sense since Razor is trying to access an internal class.

Try using a public interface

Ok so if we want to keep our class internal, we could expose it via a public interface. Our code might then look like this:

public interface IModel 
string Name {get;}
internal class MyModel : IModel
public string Name {get;set;}

Then we can change our view to be strongly typed like:

@model IModel

And it will work, however if you change your view back to be @model dynamic you will still get the exception. Pretty sure it’s because the DLR is just binding to the instance object and doesn’t really care about the interface… this makes sense.

Try using an abstract public class

For some reason if you make your internal class inherit from a public abstract class that implements the same interface you will not get this exception even though the object instance you are passing to razor is internal. For example with this structure:

public interface IModel 
string Name {get;}
public abstract class ModelBase : IModel
public abstract Name {get;}
internal class MyModel : IModel
public override string Name {get;set;}

You will not get this error if your view is @model dynamic.


I’m sure there’s something written in the DLR spec about this but still seems strange to me! If you are getting this error and you aren’t using anonymous objects for your model, hopefully this might help you figure out what is going on.

Using IoC with Umbraco & MVC

October 31, 2012 18:08

The question was asked on my post yesterday about the upcoming Umbraco 4.10.0 release with MVC support and whether it is possible to use IoC/Dependency Injection with our implementation. The answer is definitely yes!

One of the decisions we’ve made for the code of Umbraco is to not use IoC in the core. This is not because we don’t like IoC (in fact I absolutely love it) but more because things start to get really messy when not 100% of your developers understand it and use it properly. Since Umbraco is open source there are developers from many walks of life committing code to the core and we’d rather not force a programming pattern on them. Additionally, if some developers don’t fully grasp this pattern this leads to strange and inconsistent code and even worse if developers don’t understand this pattern then sometimes IoC can be very difficult to debug.

This ultimately means things are better for you since we won’t get in the way with whatever IoC framework you choose.

Which frameworks can i use?

Theoretically you can use whatever IoC framework that you’d like, though I haven’t tested or even tried most of them I’m assuming if they are reasonable frameworks that work with MVC then you should be fine. I’m an Autofac fan and to be honest I’ve only dabbled in other frameworks so all examples in this post and documentation are based on Autofac. Since we don’t use any IoC, it also means that we are not specifying a DependencyResolver so you are free to set this to whatever you like (I’d assume that most IoC frameworks would integrate with MVC via the DependencyResolver).

How do i do it?

I chucked up some docs on github here which I’ll basically just reiterate on this post again with some more points. Assuming that you construct your IoC container in your global.asax, the first thing you’ll have to do is to create this class and make sure it inherits from the Umbraco one (otherwise nothing will work). Then just override OnApplicationStarted and build up your container. Here’s an example (using Autofac):

/// <summary>
/// The global.asax class
/// </summary>
public class MyApplication : Umbraco.Web.UmbracoApplication
    protected override void OnApplicationStarted(object sender, EventArgs e)
        base.OnApplicationStarted(sender, e);

        var builder = new ContainerBuilder();

        //register all controllers found in this assembly

        //add custom class to the container as Transient instance

        var container = builder.Build();
        DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

Notice that I’ve also registered a custom class called MyAwesomeContext in to my container, this is just to show you that IoC is working. Of course you can do whatever you like with your own container :) Here’s the class:

public class MyAwesomeContext
    public MyAwesomeContext()
        MyId = Guid.NewGuid();
    public Guid MyId { get; private set; }

Next we’ll whip up a custom controller to hijack all routes for any content item that is of a Document Type called ‘Home’ (there’s documentation on github about hijacking routes too):

public class HomeController : RenderMvcController
    private readonly MyAwesomeContext _myAwesome;

    public HomeController(MyAwesomeContext myAwesome)
        _myAwesome = myAwesome;

    public override ActionResult Index(Umbraco.Web.Models.RenderModel model)
        //get the current template name
        var template = this.ControllerContext.RouteData.Values["action"].ToString();
        //return the view with the model as the id of the custom class
        return View(template, _myAwesome.MyId);

In the above controller, a new instance of MyAwesomeContext will be injected into the constructor, in the Index action we’re going to return the view that matches the currently routed template and set the model of the view to the id of the custom MyAwesomeContext object (This is just an example, you’d probably do something much more useful than this).

We can also do something similar with SurfaceControllers (or any controller you like):

public class MyTestSurfaceController : SurfaceController
    private readonly MyAwesomeContext _myAwesome;

    public MyTestSurfaceController(MyAwesomeContext myAwesome)
        _myAwesome = myAwesome;

    public ActionResult HelloWorld()
        return Content("Hello World! Here is my id " + _myAwesome.MyId);

That’s it?

Yup, these are just examples of creating controllers with IoC, the actual IoC setup is super easy and should pretty much work out of the box with whatever IoC framework you choose. However, you should probably read the ‘Things to note’ in the documentation in case your IoC engine of choice does something wacky with the controller factory.