[英]Sitecore: inject dependency into sitecore components
我使用Sitecore 8.1 MVC和Autofac作為DI。 我想知道將已解析的對象注入sitecore創建的對象(即管道,命令,計算字段等)的推薦方法是什么...例如,我使用的是成員資格提供程序,我需要調用我的業務層。 我可以在類上定義構造函數,sitecore會注入對象嗎?
謝謝
管道處理器,命令等等......基本上是Sitecore創建的任何東西 - 你相當有限。 通常的方法是使用服務定位器模式來解決依賴關系:
var membershipProvider = DependencyResolver.Current.Resolve<IMembershipProvider>()
還有其他方法。 這篇文章: https : //cardinalcore.co.uk/2014/07/02/sitecore-pipelines-commands-using-ioc-containers/使用容器工廠類來解決管道中的依賴關系。 這是使用的類:
using System;
using System.Diagnostics.CodeAnalysis;
using Sitecore.Reflection;
public class ContainerFactory : IFactory
{
private readonly IContainerManager containerManager;
public ContainerFactory() : this(new LocatorContainerManager()) // service locate an appropriate container
{
}
public ContainerFactory(IContainerManager containerManager)
{
this.containerManager = containerManager;
}
public object GetObject(string identifier)
{
Type type = Type.GetType(identifier);
return this.containerManager.Resolve(type);
}
}
然后,這將被設置為使用配置中的factory
屬性的事件或處理器的factory
。 示例配置:
<sitecore>
<events>
<event name="item:saved">
<handler factory="ContainerFactory" ref="MyApp.MyHandler, MyApp" method="MyMethod">
<database>master</database>
</handler>
</event>
</events>
<pipelines>
<MyPipeline>
<processor type="1" factory="ContainerFactory" ref="MyApp.MyProcessor, MyApp" />
</MyPipeline>
</pipelines>
<factories>
<factory id="ContainerFactory" type="MyApp.ContainerFactory"></factory>
</factories>
</sitecore>
使用第二種方法,您可以像往常一樣在構造函數中注入依賴項。
這些可能是最常用的兩種選擇。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.