Skip to content

Using Dependency Injection with Blade

Kam Figy edited this page May 30, 2013 · 1 revision

You can hook your favorite IoC container to Blade to enable you to inject dependencies into your presenters as needed.

To do this, you'll need to create your own PresenterFactory. Most likely you'll want to derive from the Blade.Configuration.ConfigurationPresenterFactory class (Synthesis.Blade.Configuration.SynthesisPresenterFactory if using Synthesis with Blade), which is the default implementation. Then simply override the ActivatePresenter method and have it construct the object using the IoC container.

Here's an example using Ninject:

  • Install the Ninject and Ninject.Web.Common NuGet packages

  • In App_Start/NinjectWebCommon.cs, configure your IoC kernel bindings/modules in the RegisterServices() method

  • Implement the injecting presenter factory: using System; using Blade; using Ninject; using Ninject.Web.Common; using Synthesis.Blade.Configuration;

      namespace MyProject.Configuration
      {
      	public class NinjectPresenterFactory : SynthesisPresenterFactory
      	{
      		protected override IPresenter<TModel> ActivatePresenter<TModel>(Type presenterType)
      		{
      			IKernel kernel = new Bootstrapper().Kernel;
      			return (IPresenter<TModel>)kernel.Get(presenterType);
      		}
      	}
      }
    
  • Configure Blade to use your injecting presenter factory in App_Config\Include\Blade.config: <presenterFactory type="MyProject.Configuration.NinjectPresenterFactory, MyProject" /> (note: if you have installed Synthesis.Blade from NuGet, this may be overridden by the Synthesis.Blade.config already, in which case change it there or remove that config patch)

  • Use constructor injection on your presenter, for example:

      public class FooPresenter : SitecorePresenter<FooModel>
      {
      	private IFoo _dependency;
      	public FooPresenter(IFoo foo)
      	{
      		_dependency = foo;
      	}
    
      	protected override FooModel GetModel(IView view, Item item)
      	{
      		return new FooModel(_dependency.GetFoo());
      	}
      }
    

Congratulations, you've now decoupled your presenter from its dependencies.

Clone this wiki locally