1

With FubuMVC, I'm not sure what the best way is to determine the current action's output model type. I see different objects that I could get the current request's URL from. But that doesn't lead to a very good solution.

What's the easiest way to get the current action's output model type from the behavior?

If this isn't a good practice, what's a better way?

4

1 回答 1

2

首先,我假设您已经在 StructureMap 中设置了设置对象,并且已经连接了 ISettingsProvider 内容。

最好、最简单的做法就是在视图中拉取设置,如下所示:

<%: Get<YourSettingsObject>().SomeSettingProperty %>

如果您坚持将这些作为输出模型的属性,请继续阅读:

假设您有一个这样的设置对象:

    public class OutputModelSettings
    {
        public string FavoriteAnimalName { get; set; }
        public string BestSimpsonsCharacter { get; set; }
    }

然后你有一个这样的输出模型:

    public class OutputModelWithSettings
    {
        public string SomeOtherProperty { get; set; }
        public OutputModelSettings Settings { get; set; }
    }

你需要做几件事:

  1. 连接 StructureMap 以便它为 Settings 对象执行 setter 注入(因此它会自动将 OutputModelSettings 注入到输出模型的“Settings”属性中。

    在您的 StructureMap 初始化代码(注册表、全局 ASAX、您的引导程序等——无论您在哪里设置容器)中设置一个设置器注入策略。

    x.SetAllProperties(s => s.Matching(p => p.Name.EndsWith("Settings")));
    
  2. 创建您的行为以在输出模型上调用 StructureMap 的“BuildUp()”以触发 setter 注入。该行为将是一个开放类型(即最后),因此它可以支持任何类型的输出模型

    public class OutputModelSettingBehavior<TOutputModel> : BasicBehavior
        where TOutputModel : class
    {
        private readonly IFubuRequest _request;
        private readonly IContainer _container;
    
        public OutputModelSettingBehavior(IFubuRequest request, IContainer container)
            : base(PartialBehavior.Executes)
        {
            _request = request;
            _container = container;
        }
    
        protected override DoNext performInvoke()
        {
            BindSettingsProperties();
    
            return DoNext.Continue;
        }
    
        public void BindSettingsProperties()
        {
            var viewModel = _request.Find<TOutputModel>().First();
            _container.BuildUp(viewModel);
        }
    }
    
  3. 创建一个约定来连接行为

    public class OutputModelSettingBehaviorConfiguration : IConfigurationAction
    {
        public void Configure(BehaviorGraph graph)
        {
            graph.Actions()
                .Where(x => x.HasOutput &&
                            x.OutputType().GetProperties()
                                .Any(p => p.Name.EndsWith("Settings")))
                .Each(x => x.AddAfter(new Wrapper(
                    typeof (OutputModelSettingBehavior<>)
                    .MakeGenericType(x.OutputType()))));
        }
    }
    
  4. 在 Routes 部分之后将约定连接到您的 FubuRegistry 中:

    ApplyConvention<OutputModelSettingBehaviorConfiguration>();
    
  5. 在您看来,使用新的设置对象:

    <%: Model.Settings.BestSimpsonsCharacter %>
    

注意:我在 Fubu 源代码中的 FubuMVC.HelloWorld 项目中将其作为工作示例提交。请参阅此提交:https ://github.com/DarthFubuMVC/fubumvc/commit/2e7ea30391eac0053300ec0f6f63136503b16cca

于 2011-03-02T20:48:54.263 回答