Using Simple Injector within your Umbraco Controllers

  • 21 Jun 2017

  • Dan Lister


Holy crap! Has it really been three years since my last blog post? What better way to make a come back than talking about the awesome Umbraco and the equally awesome Simple Injector. Hopefully this post will help you implement your own dependency injection setup within your Umbraco application.

Install Simple Injector

To install Simple Injector within your Umbraco application, use NuGet to install Simple Injector's MVC package and it's package dependencies. You can either use Visual Studio's Package Manager Console or the NuGet executable itself.

This file contains hidden or 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

Show hidden characters

Install-Package SimpleInjector.Integration.Web.Mvc

view raw step-one.cmd hosted with ❤ by GitHub

Create a Base Controller Class

Now I'm not quite sure whether this step is needed but it is always nice to create a base class for your controllers. You could always add global things such as Output Caching. Having a base controller really helps with this.

Show hidden characters

usingSystem.Web.Mvc;
usingUmbraco.Web.Models;
usingUmbraco.Web.Mvc;
namespaceMy.Controllers
{
publicclassBasePageController:SurfaceController,IRenderMvcController
{
publicvirtualActionResultIndex(RenderModelmodel)
{
returnCurrentTemplate(model);
}
protectedActionResultCurrentTemplate(Tmodel)
{
vartemplate=ControllerContext.RouteData.Values["action"].ToString();
varresult=ViewEngines.Engines.FindView(ControllerContext,template,null);
if(result.View==null||model==null)
returnnewHttpNotFoundResult();
returnView(template,model);
}
}
}

view raw step-two.cs hosted with ❤ by GitHub

Our BasePageController class will inherit from Umbraco's SurfaceController. It will also implement Umbraco's IRenderMvcController interface. The SurfaceController gives our controller access to Umbraco objects such as the CurrentPage. Implementing the IRenderMvcController interface allows our controller to be routed, since Umbraco handles all page routing for us. Within you base controller, we have 2 methods: One to load the current template and a second to find the template to use.

Create a Global Application Class

In order to setup dependency injection within our application, we'll need to create a new Global Application class where we can setup Simple Injector and register any interfaces and their implementations.

Show hidden characters

usingSystem;
usingSystem.Reflection;
usingSystem.Web.Mvc;
usingMy.Controllers;
usingSimpleInjector;
usingSimpleInjector.Integration.Web;
usingSimpleInjector.Integration.Web.Mvc;
usingUmbraco.Web;
usingUmbraco.Web.Mvc;
namespaceMy.Global
{
publicclassGlobalApplication:UmbracoApplication
{
protectedoverridevoidOnApplicationStarting(objectsender,EventArgse)
{
DefaultRenderMvcControllerResolver.Current.SetDefaultControllerType(typeof(BasePageController));
}
protectedoverridevoidOnApplicationStarted(objectsender,EventArgse)
{
varcontainer=newContainer();
container.Options.DefaultScopedLifestyle=newWebRequestLifestyle();
container.RegisterMvcControllers(Assembly.GetExecutingAssembly());
container.RegisterMvcIntegratedFilterProvider();
container.Verify();
DependencyResolver.SetResolver(newSimpleInjectorDependencyResolver(container));
}
}
}

view raw step-three.cs hosted with ❤ by GitHub

Within our global application class, we are doing two things: The first creating a new container which will hold all of our interfaces, implementations and controllers. We are also telling Umbraco and the .NET MVC application of our base controllers and dependency resolver. Lastly, we should tell our application to use our new global application class. We can do this by editing our global.asax file as follows.

Show hidden characters

<%@ Application Inherits="My.Global.GlobalApplication" Language="C#"%>

view raw step-four.asax hosted with ❤ by GitHub

Register Your Services

I'm assuming at this point you already have an interface and a class which implements a said interface. We have our Simple Injector container setup and registered with Umbraco and the application. Next we need to specify what implementations to use when interface dependencies are required within in our controller. To do this, we need to register each within our global application class, specifying the interface and implementation. It is also important to specify the lifestyle of the registration. This affects how and when implementations are created for each registration. For example, below we are using a scoped lifestyle and as the scoped lifestyle defined is a per web request scope, we will only find one instance of the registration per web request. Transient and Singleton or other examples of lifestyles.

Show hidden characters

// One instance for web request
container.Register<IScopedService,ScopedService>(Lifestyle.Scoped);
// One instance for application created
container.Register<ISingletonService,SingletonService>(Lifestyle.Singleton);
// New instance every time a dependency is used
container.Register<ITransientService,TransientService>(Lifestyle.Transient);

view raw step-five.cs hosted with ❤ by GitHub

Inject the Dependencies

All we have to do now is amend our controller to be dependant of a specific interface. As we have registered our implementations, the controllers will not care about what implementation it is given. The controller will be pretty happy to assume the given dependency conforms to the interface referenced. This makes testing our controllers quite easy. For example, we can mock our dependencies so that testing the controller becomes the sole purpose of our tests. So lets add some dependencies to our controller's constructor.

Show hidden characters

usingSystem.Web.Mvc;
usingMy.Services;
namespaceMy.Controllers
{
publicclassHomePageController:BasePageController
{
privatereadonlyIScopedService_scopedService;
publicHomePageController(IScopedServicescopedService)
{
_scopedService=scopedService;
}
publicActionResultHomePage()
{
varmodel=_scopedService.SomeMethodName();
returnCurrentTemplate(model);
}
}
}

view raw step-six.cs hosted with ❤ by GitHub

I think that explains everything or at least gives you the basics with regards to setting dependency injection, within Umbraco, using Simple Injector. If I've missed anything or you have spotted a mistake, please feel free to tweet me.


Disqus Comments

We were unable to load Disqus. If you are a moderator please see our troubleshooting guide.

G

Start the discussion…

Comment

Log in with
or sign up with Disqus or pick a name

Disqus is a discussion network

  • Don't be a jerk or do anything illegal. Everything is easier that way.

Read full terms and conditions

This comment platform is hosted by Disqus, Inc. I authorize Disqus and its affiliates to:

  • Use, sell, and share my information to enable me to use its comment services and for marketing purposes, including cross-context behavioral advertising, as described in our Terms of Service and Privacy Policy, including supplementing that information with other data about me, such as my browsing and location data.
  • Contact me or enable others to contact me by email with offers for goods or services
  • Process any sensitive personal information that I submit in a comment. See our Privacy Policy for more information

Acknowledge I am 18 or older

I'd rather post as a guest

  • 3

  • Discussion Favorited!

Favoriting means this is a discussion worth sharing. It gets shared to your followers' Disqus feeds, and gives the creator kudos!

Find More Discussions

Share

  • Tweet this discussion

    • Share this discussion on Facebook
    • Share this discussion via email
    • Copy link to discussion
  • Best

Be the first to comment.

Load more comments

live.rezync.com

live.rezync.com is blocked

This page has been blocked by an extension

  • Try disabling your extensions.

ERR_BLOCKED_BY_CLIENT

Reload

This page has been blocked by an extension

pippio.com

pippio.com is blocked

This page has been blocked by an extension

  • Try disabling your extensions.

ERR_BLOCKED_BY_CLIENT

Reload

This page has been blocked by an extension