0

我需要在我的公司实现 MVC 架构,所以任何人都可以建议在哪里保留常用方法以在所有页面上调用。喜欢:

状态 ddl、部门 ddl 以及角色列表等...

请给我建议将它们保存在建筑中的位置。

谢谢

4

1 回答 1

2

根据应用程序的规模,有不同的解决方案。对于小型项目,您可以简单地在 MVC 应用程序本身中创建一组类。只需创建一个 Utils 文件夹和一个 DropDownLists 类就可以了。对于像这样简单的东西,我发现使用返回所需数据、列表或枚举的静态方法是可以接受的。

另一种选择是创建一个派生自 Controller 的抽象 MyControllerBase 类,并将您的横切关注点放在其中,可能作为虚拟方法或属性。然后你所有的实际控制器都可以从 MyControllerBase 下降。

对于较大的应用程序,或者在您可能与其他 MVC 应用程序共享这些类的情况下,创建一个共享库,例如 MySolution.Utils 并根据需要从所有项目中引用该库。

更大解决方案的另一种可能性是使用依赖注入在运行时注入需求。您可能会考虑使用 Unity 或 Ninject 之类的工具来完成此任务。

示例,根据您的要求(也在 GitHub Gist 中

// declare these in a shared library
public interface ILookupDataProvider
{
    IEnumerable<string> States { get; }
} 

public class LookupDataProvider: ILookupDataProvider
{
    public IEnumerable<string> States
    {
        get
        {
            return new string[] { "A", "B", "C" };
        }
    }
}

// then inject the requirement in to your controller
// in this example, the [Dependency] attribute comes from Unity (other DI containers are available!)
public class MyController : Controller
{
    [Dependency]
    public ILookupDataProvider LookupDataProvider { get; set; }

    public ActionResult Index()
    {
        var myModel = new MyModel
        {
            States = LookupDataProvider.States
        };

        return View(myModel);
    }
}

在上面的代码中,您需要配置依赖注入技术,但这绝对超出了答案的范围(在此处查看 SO 以获取帮助)。一旦配置正确,ILookupDataProvider 的具体实现将在运行时注入以提供数据。

我建议的一个最终解决方案是在 WCF 服务层中托管共享服务,尽管对于小型项目来说这将是非常过分的。如果将来需要,这允许您的应用程序的某些部分被分离到高度可扩展的服务中。

于 2013-10-28T22:55:39.703 回答