Created
April 5, 2013 15:03
-
-
Save esteewhy/5319979 to your computer and use it in GitHub Desktop.
DD4T model builders must die. But before that they must learn to play nicely with Unity DI. Here's how.
This file contains 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
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using Microsoft.Practices.ServiceLocation; | |
using Microsoft.Practices.Unity; | |
namespace Alitalia.ConsumerWeb.Mapping.Tridion | |
{ | |
public class BuilderFactory | |
{ | |
private static readonly IDictionary<string, IBuilder> BuilderCache = new Dictionary<string, IBuilder>(); | |
private static IUnityContainer container; | |
public static IBuilder GetBuilder(string viewName) | |
{ | |
IBuilder builder; | |
if (!BuilderCache.TryGetValue(viewName, out builder)) | |
{ | |
Type builderType = typeof(BuilderFactory).Assembly.GetTypes() | |
.FirstOrDefault(t => typeof(IBuilder).IsAssignableFrom(t) && t.Name.StartsWith(viewName)); | |
if (builderType != null) | |
{ | |
builder = GetContainer().Resolve(builderType) as IBuilder; | |
if (builder != null) | |
BuilderCache.Add(viewName, builder); | |
} | |
} | |
return builder; | |
} | |
private static IUnityContainer GetContainer() | |
{ | |
return container ?? (container = ServiceLocator.Current.GetInstance<IUnityContainer>()); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment