2016-06-30 55 views
4

我使用Sitecore 8.1 MVC和Autofac作爲DI。我想知道什麼是推薦的方式注入解析對象到sitecore創建的對象,即管道,命令,計算字段等...作爲一個例子,我使用的是我需要調用我的業務層的成員資格提供者。我有可能在類上定義一個構造函數,sitecore會注入這些對象嗎?Sitecore:將依賴注入到sitecore組件

感謝

回答

3

用之類的東西流水線處理器,命令等等...基本上任何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屬性的事件或處理器。配置示例:

<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> 

使用第二種方法,您可以像往常一樣在構造函數中注入依賴關係。

這些可能是2個最常用的選項。

+0

只要注意服務定位器和俘虜依賴。你會想在'try/finally'中執行釋放 –