2

在 Web 表单中,我会在我的模型中使用构造函数依赖注入,如下所示:

[SitecoreType(AutoMap = true)]
public class Article
{
    private readonly ICommonService _commonService;

    public Article(ICommonService commonService)
    {
        _commonService = commonService;
    }

    [SitecoreId]
    private Guid Id { get; set; }

    public string Title { get; set; }

    [SitecoreIgnore]
    public string GetTestString
    {
        get { return _commonService.GetTestString(); }
    }
}

这里的想法是将逻辑移动到服务中并与 DI 保持松散耦合。因此,Glass 提供了原始的 Sitecore 数据,然后服务帮助处理该数据或提取额外数据以完成模型。

是否可以参考解析 DI 的模型进行视图渲染并且模型可以使用?:@inherits Glass.Mapper.Sc.Web.Mvc.GlassView

目前,当我尝试这样做时,我得到 No parameterless constructor defined for this object

我可以通过使用控制器并通过控制器将依赖项传递给模型来完成上述工作。

是否有可能在简单的视图渲染中进行这项工作,从而为除了简单的 Glass ORM 数据之外还需要逻辑的模型创建控制器视图?

目前发布在 Glass Mapper Google Group 中:https ://groups.google.com/forum/#!topic/glasssitecoremapper/BJnfQGXR7S8

4

2 回答 2

2

您可以ObjectConstruction为此使用管道。您需要添加一个IObjectConstructionTask使用 IoC 容器实现和解析您的类的新类,即:

public class IoCResolvingTask : IObjectConstructionTask
{
    public virtual void Execute(ObjectConstructionArgs args)
    {
        // check that no other task has created an object and that this is a dynamic object
        if (args.Result != null || args.Configuration.Type.IsAssignableFrom(typeof(IDynamicMetaObjectProvider))) return;

        // create instance using your container
        var obj = Container.Resolve(args.Configuration.Type);

        // map properties from item to model
        args.Configuration.MapPropertiesToObject(obj, args.Service, args.AbstractTypeCreationContext);

        // set the new object as the returned result
        args.Result = obj;
    }
}

然后你需要将你的任务注册到 Glass:

public static void CastleConfig(IWindsorContainer container){
    var config = new Config();

    container.Register(Component.For<IObjectConstructionTask>().ImplementedBy<IoCResolvingTask>().LifestylePerWebRequest());

    container.Install(new SitecoreInstaller(config));
}
于 2015-02-20T06:56:43.187 回答
0

是否可以参考解析 DI 的模型进行视图渲染并且模型可以使用?:@inherits Glass.Mapper.Sc.Web.Mvc.GlassView

答案是可以的。

在模型中,DI 会自动解析。从控制器和其他领域我求助于使用服务定位器模式:https ://msdn.microsoft.com/en-us/library/ff648968.aspx

我遇到的问题是设置和配置。这是我为使其成功运行而实现的代码。

glassMapperCustom.cs

 public static void CastleConfig(IWindsorContainer container)
    {
        var config = new Config { UseWindsorContructor = true };

        container.Install(new SitecoreInstaller(config));
        container.Install(new ServiceInstaller());
    }  

服务安装程序代码

public void Install(IWindsorContainer container, IConfigurationStore store)
    {
        container.Register(
            Component.For<ICustomService>().ImplementedBy<CustomService>().LifestyleTransient(),            
            Component.For<SitecoreController>().ImplementedBy<SitecoreController>().LifestylePerWebRequest()
                .DependsOn(new { databaseName = Sitecore.Context.Database }));

        // Set up the servicelocator. We can use this in the code to get instances of services.
        ServiceLocator.SetLocatorProvider(() =>
                    new WindsorServiceLocator(container));
    }

全球.asax

   public static void RegisterRoutes(RouteCollection routes)
    {
        routes.MapRoute(
            "SiteName", // Route name 
            "SiteName/{controller}/{action}/{id}", // URL with parameters 
            new { controller = "Home", action = "Index", id = System.Web.Mvc.UrlParameter.Optional }); // Parameter defaults 
    }

    /// <summary>
    /// Registers the global filters.
    /// </summary>
    /// <param name="filters">Global filter collection.</param>
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new HandleErrorAttribute());
    }

    /// <summary>
    /// Will be called when the application first starts.
    /// </summary>
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);
    }
于 2015-05-29T08:27:01.037 回答