如何在ASP.NET MVC中使用DRY原则来重构此代码?

Mik*_*osa 4 c# asp.net-mvc coding-style dry

我的一个控制器中有几种方法可以做到这一点:

ViewData["Customers"] = LoadCustomers();
ViewData["Employees"] = LoadEmployees();
ViewData["Statuses"] = LoadStatuses();
etc......
Run Code Online (Sandbox Code Playgroud)

这是LoadCustomers(),但LoadEmployees,LoadStatuses和所有其他几乎完全相同的逻辑:

private static SelectList LoadCustomers()
    {
        IList<Customer> customers;
        try
        {
            IServiceCallService scService = new ServiceCallService();
            customers = scService.GetCustomers();
            Customer c = new Customer
            {
                ID = "",
                Name = "-- Select a Facility --"
            };
            customers.Insert(0, c);
        }
        catch
        {
            customers = new List<Customer>();
            Customer c = new Customer
            {
                ID = "",
                Name = "-- No Facilities on File --"
            };
            customers.Insert(0, c);
        }

        return new SelectList(customers, "ID", "Name");
    }
Run Code Online (Sandbox Code Playgroud)

如何更好地编写此代码,以便每次添加新的选择列表时都不需要新方法?

Joh*_*lla 5

看起来它可能是泛型的一个很好的候选者:

private static SelectList LoadItems<T>() where T : new, ... 
{                                                // Add any additional interfaces
                                                 // that need to be supported by T
                                                 // for your Load method to work,
                                                 // as appropriate.
    IList<T> items;
    try
    {
        IServiceCallService scService = new ServiceCallService();
        results = scService.Get<T>();  // You'll need to replace GetCustomers() with
                                       //   a generic Get<T> method.

        // ...
    }
    catch         // Really needed? What are you trying to catch here? (This catches
    {             //   everything silently. I suspect this is overkill.)
        // ...
    }

    return new SelectList(items, "ID", "Name");
}
Run Code Online (Sandbox Code Playgroud)