我将在Sitecore 8.1 MVC项目中实现城堡windsor DI。在网站级别我也创建了界面,类和存储库。我已经阅读了各种文章,但没有找到直接的方法。 控制器部分如下:
public class CommonController : Controller
{
private readonly ICommon _service;
public CommonController(ICommon commonService)
{
this._service = commonService;
}
public ActionResult GetProductDetail()
{
var CommonModel = _service.GetProductDetail();
return View(CommonModel);
}
}
浏览时出现以下错误:
Server Error in '/' Application.
No parameterless constructor defined for this object.
我知道仍然需要实施DI部分。
我已经完成了以下文章的解决方案:Using Castle Windsor with Sitecore MVC for Dependency Injection
但现在出现以下错误:
字典中没有给定的密钥。描述:发生了未处理的异常。
有什么建议吗?
答案 0 :(得分:1)
本文将介绍如何配置windsor。但它没有告诉你的是你必须配置你的容器。
要让windsor能够解析您的ICommon commonService,您需要告诉它如何执行此操作。
有几种方法可以做到这一点。以下是我在一个项目中如何使用它的一个例子。
希望它对你有所帮助。
汉斯
public class WebInstaller : IWindsorInstaller
{
public void Install(IWindsorContainer container, IConfigurationStore store)
{
container.Register(Component.For(typeof(ICommon)).ImplementedBy(typeof(CommonService)).LifestyleTransient());
}
}
public static class DependencyInjection
{
private static IWindsorContainer container;
private static readonly object padlock = new object();
public static IWindsorContainer Container
{
get
{
lock (padlock)
{
if (container == null)
{
InitializeDependencyInjection();
}
return container;
}
}
}
private static void InitializeDependencyInjection()
{
container = new WindsorContainer();
container.AddFacility<FactorySupportFacility>();
container.Kernel.Resolver.AddSubResolver(new ArrayResolver(container.Kernel));
container.Install(new Core.Installers.WebInstaller());
// Wiring up DI for the SOLR integration
//new WindsorSolrStartUp(container).Initialize();
}
/// <summary>
/// http://www.superstarcoders.com/blogs/posts/using-castle-windsor-with-sitecore-mvc-for-dependency-injection.aspx
/// </summary>
public static void SetupControllerFactory()
{
Container.Install(FromAssembly.This());
// Transient needed for sitecore running multiple instances of a controller for controller renderings
Container.Register(Classes.FromThisAssembly().BasedOn<IController>().LifestyleTransient());
IControllerFactory controllerFactory = new WindsorControllerFactory(Container);
var scapiSitecoreControllerFactory = new SitecoreControllerFactory(controllerFactory);
ControllerBuilder.Current.SetControllerFactory(scapiSitecoreControllerFactory);
}
}
public class InitializeWindsorControllerFactory
{
public virtual void Process(PipelineArgs args)
{
DependencyInjection.SetupControllerFactory();
}
}