Home > c# > Creating various types of menus using dependency injection

Creating various types of menus using dependency injection

June 15Hits:1
Advertisement

I am here to discuss what are the possible improvement can be made in order to make the following code covering all the principles of programming paradigm ( SOLID , DRY ...etc ). Basically, I am practicing Design Patterns.

Example to create multiple types if Cascade Dropdown list of different types ( single select / multiple select items ):

public class MyListType {     public string ID { get; set; }     public string ComplexID { get; set; }     public string Name { get; set; }     public bool Selected { get; set; } }   public class DropDownItem {     public string Value { get; set; }     public string Name { get; set; } }  public class AdminItem {     public string ID { get; set; }     public string AdminName { get; set; } }  public class MerchantItem {     public string ID { get; set; }     public string MerchantName { get; set; } }  public class CustomerItem {     public string ID { get; set; }     public string CustomerName { get; set; } }  public enum DefaultDDItems {      ALL = 0,      All_Selected = 1,      NoDefault,      First_Selected,      CurrentMonth,      CurrentYear  }  public interface IDropDown {     MultiSelectList GetMultiSelectDropDown();     MultiSelectList GetMultiSelectDropDown(DefaultDDItems defaultDdItem);     List<SelectListItem> GetSingleSelectDropDown();     List<SelectListItem> GetSingleSelectDropDown(DefaultDDItems defaultDdItem); }  public class AdminLevelDropDown : IDropDown {     private List<AdminItem> _adminItemes;     private string[] _selectedIds;      public AdminLevelDropDown()     {     }      public AdminLevelDropDown(List<AdminItem> items)     {         this._adminItemes = items;     }      public AdminLevelDropDown(List<AdminItem> items, string[] defaultSelectedItems)     {         this._adminItemes = items;         this._selectedIds = defaultSelectedItems;     }      public MultiSelectList GetMultiSelectDropDown()     {         return GetMultiSelectDropDown(DefaultDDItems.NoDefault);     }      public MultiSelectList GetMultiSelectDropDown(DefaultDDItems defaultDdItem)     {         var mylist = new List<MyListType>();          if (_adminItemes == null)         {             return new MultiSelectList(mylist, "ID", "Name");         }          if (!_adminItemes.Any())         {             return new MultiSelectList(mylist, "ID", "Name");         }          switch (defaultDdItem)         {             case DefaultDDItems.ALL:                 mylist.Add(new MyListType()                     {                         Name = "All",                         ID = "0"                     });                 break;              case DefaultDDItems.All_Selected:                 mylist.Add(new MyListType()                     {                         Name = "All",                         ID = String.Join(",", _adminItemes)                     });                 break;               // Other switch cases can be implemented here         }          mylist.AddRange(_adminItemes.Select(i => new MyListType()             {                 Name = i.AdminName,                 ID = i.ID             }).ToList());          return new MultiSelectList(mylist, "ID", "Name", _selectedIds);      }      public List<SelectListItem> GetSingleSelectDropDown()     {         return GetSingleSelectDropDown(DefaultDDItems.NoDefault);     }      public List<SelectListItem> GetSingleSelectDropDown(DefaultDDItems defaultDdItem)     {         var mylist = new List<SelectListItem>();          if (_adminItemes == null)         {             return new List<SelectListItem>(0);         }          if (!_adminItemes.Any())         {             return new List<SelectListItem>(0);         }          switch (defaultDdItem)         {             case DefaultDDItems.ALL:                 mylist.Add(new SelectListItem()                 {                     Value = "All",                     Text = "0"                 });                 break;              case DefaultDDItems.All_Selected:                 mylist.Add(new SelectListItem()                 {                     Value = "All",                     Text = String.Join(",", _adminItemes)                 });                 break;         }          mylist.AddRange(_adminItemes.Select(i => new SelectListItem()         {             Text = i.AdminName,             Value = i.ID,             Selected = _selectedIds.FirstOrDefault() == i.ID         }).ToList());          return mylist;     } }  public class MerchantLevelDropDown : IDropDown {      private List<MerchantItem> _merchantItemes;     private string[] _selectedIds;       public MerchantLevelDropDown()     {     }      public MerchantLevelDropDown(List<MerchantItem> items)     {         this._merchantItemes = items;     }      public MerchantLevelDropDown(List<MerchantItem> items, string[] defaultSelectedItems)     {         this._merchantItemes = items;         this._selectedIds = defaultSelectedItems;     }       public MultiSelectList GetMultiSelectDropDown()     {         return GetMultiSelectDropDown(DefaultDDItems.NoDefault);     }      public MultiSelectList GetMultiSelectDropDown(DefaultDDItems defaultDdItem)     {         var mylist = new List<MyListType>();          if (_merchantItemes == null)         {             return new MultiSelectList(mylist, "ID", "Name");         }          if (!_merchantItemes.Any())         {             return new MultiSelectList(mylist, "ID", "Name");         }          switch (defaultDdItem)         {             case DefaultDDItems.ALL:                 mylist.Add(new MyListType()                 {                     Name = "All",                     ID = "0"                 });                 break;              case DefaultDDItems.All_Selected:                 mylist.Add(new MyListType()                 {                     Name = "All",                     ID = String.Join(",", _merchantItemes)                 });                 break;         }          mylist.AddRange(_merchantItemes.Select(i => new MyListType()         {             Name = i.MerchantName,             ID = i.ID         }).ToList());          return new MultiSelectList(mylist, "ID", "Name", _selectedIds);     }      public List<SelectListItem> GetSingleSelectDropDown()     {         return GetSingleSelectDropDown(DefaultDDItems.NoDefault);     }      public List<SelectListItem> GetSingleSelectDropDown(DefaultDDItems defaultDdItem)     {         var mylist = new List<SelectListItem>();          if (_merchantItemes == null)         {             return new List<SelectListItem>(0);         }          if (!_merchantItemes.Any())         {             return new List<SelectListItem>(0);         }          switch (defaultDdItem)         {             case DefaultDDItems.ALL:                 mylist.Add(new SelectListItem()                 {                     Value = "All",                     Text = "0"                 });                 break;              case DefaultDDItems.All_Selected:                 mylist.Add(new SelectListItem()                 {                     Value = "All",                     Text = String.Join(",", _merchantItemes)                 });                 break;         }          mylist.AddRange(_merchantItemes.Select(i => new SelectListItem()         {             Text = i.MerchantName,             Value = i.ID,             Selected = _selectedIds.FirstOrDefault() == i.ID         }).ToList());          return mylist;     } }  public class CustomerLevelDropDown : IDropDown {      private List<CustomerItem> _customerItemes;     private string[] _selectedIds;       public CustomerLevelDropDown()     {     }      public CustomerLevelDropDown(List<CustomerItem> items)     {         this._customerItemes = items;     }      public CustomerLevelDropDown(List<CustomerItem> items, string[] defaultSelectedItems)     {         this._customerItemes = items;         this._selectedIds = defaultSelectedItems;     }       public MultiSelectList GetMultiSelectDropDown()     {         return GetMultiSelectDropDown(DefaultDDItems.NoDefault);     }      public MultiSelectList GetMultiSelectDropDown(DefaultDDItems defaultDdItem)     {         var mylist = new List<MyListType>();          if (_customerItemes == null)         {             return new MultiSelectList(mylist, "ID", "Name");         }          if (!_customerItemes.Any())         {             return new MultiSelectList(mylist, "ID", "Name");         }          switch (defaultDdItem)         {             case DefaultDDItems.ALL:                 mylist.Add(new MyListType()                 {                     Name = "All",                     ID = "0"                 });                 break;              case DefaultDDItems.All_Selected:                 mylist.Add(new MyListType()                 {                     Name = "All",                     ID = String.Join(",", _customerItemes)                 });                 break;         }          mylist.AddRange(_customerItemes.Select(i => new MyListType()         {             Name = i.CustomerName,             ID = i.ID         }).ToList());          return new MultiSelectList(mylist, "ID", "Name", _selectedIds);     }      public List<SelectListItem> GetSingleSelectDropDown()     {         return GetSingleSelectDropDown(DefaultDDItems.NoDefault);     }      public List<SelectListItem> GetSingleSelectDropDown(DefaultDDItems defaultDdItem)     {         var mylist = new List<SelectListItem>();          if (_customerItemes == null)         {             return new List<SelectListItem>(0);         }          if (!_customerItemes.Any())         {             return new List<SelectListItem>(0);         }          switch (defaultDdItem)         {             case DefaultDDItems.ALL:                 mylist.Add(new SelectListItem()                 {                     Value = "All",                     Text = "0"                 });                 break;              case DefaultDDItems.All_Selected:                 mylist.Add(new SelectListItem()                 {                     Value = "All",                     Text = String.Join(",", _customerItemes)                 });                 break;         }          mylist.AddRange(_customerItemes.Select(i => new SelectListItem()         {             Text = i.CustomerName,             Value = i.ID,             Selected = _selectedIds.FirstOrDefault() == i.ID         }).ToList());          return mylist;     } }   public interface IDropdownFactory {     AdminLevelDropDown GetMultiSelect_AdminDropDown();     AdminLevelDropDown GetMultiSelect_AdminDropDown(List<AdminItem> items);     AdminLevelDropDown GetMultiSelect_AdminDropDown(List<AdminItem> items, string[] selecteditems);      AdminLevelDropDown GetSingleSelect_AdminDropDown();     AdminLevelDropDown GetSingleSelect_AdminDropDown(List<AdminItem> items);     AdminLevelDropDown GetSingleSelect_AdminDropDown(List<AdminItem> items, string[] selectedItems);         MerchantLevelDropDown GetMultiSelect_MerchantDropDown();     MerchantLevelDropDown GetMultiSelect_MerchantDropDown(List<MerchantItem> items);     MerchantLevelDropDown GetMultiSelect_MerchantDropDown(List<MerchantItem> items, string[] selecteditems);      MerchantLevelDropDown GetSingleSelect_MerchantDropDown();     MerchantLevelDropDown GetSingleSelect_MerchantDropDown(List<MerchantItem> items);     MerchantLevelDropDown GetSingleSelect_MerchantDropDown(List<MerchantItem> items, string[] selectedItems);        CustomerLevelDropDown GetMultiSelect_CustomerDropDown();     CustomerLevelDropDown GetMultiSelect_CustomerDropDown(List<CustomerItem> items);     CustomerLevelDropDown GetMultiSelect_CustomerDropDown(List<CustomerItem> items, string[] selecteditems);      CustomerLevelDropDown GetSingleSelect_CustomerDropDown();     CustomerLevelDropDown GetSingleSelect_CustomerDropDown(List<CustomerItem> items);     CustomerLevelDropDown GetSingleSelect_CustomerDropDown(List<CustomerItem> items, string[] selectedItems);  }  public class DropDownFactory : IDropdownFactory {      public AdminLevelDropDown GetMultiSelect_AdminDropDown()     {         return new AdminLevelDropDown();     }      public AdminLevelDropDown GetMultiSelect_AdminDropDown(List<AdminItem> items)     {         return new AdminLevelDropDown(items);     }      public AdminLevelDropDown GetMultiSelect_AdminDropDown(List<AdminItem> items, string[] selecteditems)     {         return new AdminLevelDropDown(items, selecteditems);     }      public AdminLevelDropDown GetSingleSelect_AdminDropDown()     {         return new AdminLevelDropDown();     }      public AdminLevelDropDown GetSingleSelect_AdminDropDown(List<AdminItem> items)     {         return new AdminLevelDropDown(items);     }      public AdminLevelDropDown GetSingleSelect_AdminDropDown(List<AdminItem> items, string[] selectedItems)     {         return new AdminLevelDropDown(items, selectedItems);     }      public MerchantLevelDropDown GetMultiSelect_MerchantDropDown()     {         return new MerchantLevelDropDown();     }      public MerchantLevelDropDown GetMultiSelect_MerchantDropDown(List<MerchantItem> items)     {         return new MerchantLevelDropDown(items);     }      public MerchantLevelDropDown GetMultiSelect_MerchantDropDown(List<MerchantItem> items, string[] selecteditems)     {         return new MerchantLevelDropDown(items, selecteditems);     }      public MerchantLevelDropDown GetSingleSelect_MerchantDropDown()     {         return new MerchantLevelDropDown();     }      public MerchantLevelDropDown GetSingleSelect_MerchantDropDown(List<MerchantItem> items)     {         return new MerchantLevelDropDown(items);     }      public MerchantLevelDropDown GetSingleSelect_MerchantDropDown(List<MerchantItem> items, string[] selectedItems)     {         return new MerchantLevelDropDown(items, selectedItems);     }      public CustomerLevelDropDown GetMultiSelect_CustomerDropDown()     {         return new CustomerLevelDropDown();     }      public CustomerLevelDropDown GetMultiSelect_CustomerDropDown(List<CustomerItem> items)     {         return new CustomerLevelDropDown(items);     }      public CustomerLevelDropDown GetMultiSelect_CustomerDropDown(List<CustomerItem> items, string[] selecteditems)     {         return new CustomerLevelDropDown(items, selecteditems);     }      public CustomerLevelDropDown GetSingleSelect_CustomerDropDown()     {         return new CustomerLevelDropDown();     }      public CustomerLevelDropDown GetSingleSelect_CustomerDropDown(List<CustomerItem> items)     {         return new CustomerLevelDropDown(items);     }      public CustomerLevelDropDown GetSingleSelect_CustomerDropDown(List<CustomerItem> items, string[] selectedItems)     {         return new CustomerLevelDropDown(items, selectedItems);     } } 

IoC Using AutoFac:

var container = new Container(); container.RegisterType<DropDownFactory>().As<IDropdownFactory>().InstancePerHttpRequest(); 

Controller:

public class HomeController : Controller {     public IDropdownFactory _dropdownFactory;      public HomeController(IDropdownFactory dropdownFactory)     {         this._dropdownFactory = dropdownFactory;     }      public ViewResult GetMultiSelect_AdminDropDown(string[] selectedids)     {         var adminItems = _adminRepo.GetAdminItems();          var adminDD = _dropdownFactory.GetMultiSelect_AdminDropDown(adminItems, selectedids);         return View(adminDD);      }      public ViewResult GetSingleSelect_AdminDropDown(string[] selectedids)     {         var adminItems = _adminRepo.GetAdminItems();          var adminDD = _dropdownFactory.GetSingleSelect_AdminDropDown(adminItems, selectedids);         return View(adminDD);      }      public ViewResult GetMultiSelect_MerchantDropDown(string[] selectedids)     {         var merchantItems = _merchantRepo.GetMerchantItems();          var merchantDD = _dropdownFactory.GetMultiSelect_MerchantDropDown(merchantItems, selectedids);         return View(merchantDD);     }      public ViewResult GetSingleSelect_MerchantDropDown(string[] selectedids)     {         var merchantItems = _merchantRepo.GetMerchantItems();          var merchantDD = _dropdownFactory.GetSingleSelect_MerchantDropDown(merchantItems, selectedids);         return View(merchantDD);     }      public ViewResult GetMultiSelect_CustomerDropDown(string[] selectedids)     {         var customerItems = _customerRepo.GetCustomerItems();          var merchantDD = _dropdownFactory.GetMultiSelect_CustomerDropDown(customerItems, selectedids);         return View(merchantDD);     }      public ViewResult GetSingleSelect_CustomerDropDown(string[] selectedids)     {         var customerItems = _customerRepo.GetCustomerItems();          var merchantDD = _dropdownFactory.GetSingleSelect_CustomerDropDown(customerItems, selectedids);         return View(merchantDD);     }  } 

Answers

Some quick remarks:

  • Be consistent in your capitalization: DropDownFactory vs IDropdownFactory.
  • GetMultiSelect_AdminDropDown (etc.): DO NOT use underscores, hyphens, or any other nonalphanumeric characters.
  • selecteditems is a compound word, so it should be selectedItems. Ditto selectedids,...
  • DefaultDDItems: Use a singular name for most Enum types, but use a plural name for Enum types that are bit fields. Also: don't use an acronym ("DD"). And why assign values to two of the enum entries, but not all? Also: don't use underscores. And why is ALL all capitals?
  • I see plenty of magic strings that should be constants: "ID", "Name", "All",...
  • There's a typo in _adminItemes. And _merchantItemes.
  • Why does AdminItem have an AdminName, and MerchantItem a MerchantName (etc.)? Why not simply use Name?
  • A lot of this code looks like it's copy-pasted and then a search/replace was executed to change Admin to Merchant etc. -- hence the same typos appearing in multiple places. Once you do that, you should realize that you need to make this piece of code more abstract and for instance put it in a base class.
  • DropDownFactory isn't a factory how I understand the concept.

Related Articles

  • Creating various types of menus using dependency injectionJune 15

    I am here to discuss what are the possible improvement can be made in order to make the following code covering all the principles of programming paradigm ( SOLID , DRY ...etc ). Basically, I am practicing Design Patterns. Example to create multiple

  • How to create a static instance of a dependency injected class?January 16

    I've defined a class which takes a repository instance as the sole constructor argument. And now that I created a static instance of that class, MainViewModel the constructor arguments need to be specified. Issue: In order to specify the required arg

  • DB connection Dependency Injection and static creator methodsJune 17

    I often use static "factory" methods to create objects from database. class Job { protected $objDb; public function __construct($objDb) { $this->objDb = $objDb; } public static function LoadArrayByProjectId($intProjectId, $objDd) { //some cod

  • How to do dependency Injection and conditional object creation based on type?November 19

    I have a service endpoint initialized using DI. It is of the following style. This end point is used across the app. public class CustomerService : ICustomerService { private IValidationService ValidationService { get; set; } private ICustomerReposit

  • Dependency injection: At what point am I allowed to create a new object?October 31

    I am refactoring a PHP application, and I am trying to do has much dependency injection (DI) as possible. I feel like I've got a good grasp of how it works, and I can certainly see my classes becoming a lot leaner and more robust. I'm refactoring so

  • Can Dependency Injection used as an alternative to Reflection for creating instancesNovember 9

    There is a piece of .net C# code which use Reflection to create an instance using Activator.CreateInstance(). This is an old piece of code and runs on the top of Enterprise Library. Is it a better idea to replace this with Dependency Injection to cre

  • Dependency Injection with classes which are created oftenMay 25

    I have a question about dependency injection and best practices when using simple classes which are meant to be created often, which have dependencies on external services. Here's a (vastly) simplified version of what I'm working on: app.js import {F

  • Questioning one of the arguments for dependency injection: Why is creating an object graph hard?August 21

    Dependency injection frameworks like Google Guice give the following motivation for their usage (source): To construct an object, you first build its dependencies. But to build each dependency, you need its dependencies, and so on. So when you build

  • Do retail games use "inversion of control" and "dependency injection"?August 25

    Many of the more diligent software developers I know are moving to inversion of control and dependency injection to handle references to objects. Coming from a Flash games perspective I don't know all the ins and outs of AAA studios, so: are these us

  • Gradual approaches to dependency injectionJanuary 29

    I'm working on making my classes unit-testable, using dependency injection. But some of these classes have a lot of clients, and I'm not ready to refactor all of them to start passing in the dependencies yet. So I'm trying to do it gradually; keeping

  • Is this pattern of optional dependency injection sound? January 29

    I'm working on making my classes unit-testable, using dependency injection. But some of these classes have a lot of clients, and I'm not ready to refactor all of them to start passing in the dependencies yet. So I'm trying to do it gradually; keeping

  • Use Dependency Injection For Data Objects?June 10

    I'm just learning about dependency injection, and am stuck on something. Dependency Injection recommends sending dependent classes through the constructor, but I'm wondering if this is necessary for data objects. Since the Unit-Testability is one of

  • Entity collection best practice (separation of concerns, dependency injection, -)February 14

    I build a collection to ensure only valid entities in an array so I don't have to validate after every function / method call as I could rely on the collection to have only valid entities stored. class WorldCollection implements Collection, ArrayAcce

  • Why was dependency injection pattern not included in the Gang of four?February 20

    Why was the dependency injection pattern not incluided in the gang of four? Did GOF pre-date widespread automated testing? Is dependency injection now considered a core pattern? --------------Solutions------------- I was Editor of Software Developmen

  • When is it not appropriate to use the dependency injection pattern?February 20

    Since learning (and loving) automated testing I have found myself using the dependency injection pattern in almost every project. Is it always appropriate to use this pattern when working with automated testing? Are there any situations were you shou

  • How to convert my classes to Dependency injection?February 27

    I am still learning to develop my skills in OOP. It uses a combination of the factory and its real singletons? As I did more research, I have realized this design pattern is bad because of global state and it is hard to test. I can't figure how how t

  • Is dependency injection essential for unit testing?March 22

    Is using dependency injection (DI) essential for unit testing? I can't think of another alternative for isolating code so it can be tested. Also, all the examples I have ever seen use this pattern. Is that because it is the only viable option or are

  • Dependency injection: How to sell it May 23

    Let it be known that I am a big fan of dependency injection (DI) and automated testing. I could talk all day about it. Background Recently, our team just got this big project that is to built from scratch. It is a strategic application with complex b

  • Storage class, dependency injection and singletonsJuly 24

    In re-writing my PHP framework vervPHP, I've created the following class: class storage { private static $instance; public $db = null; // Holds a database connection object public $user = null; // Holds user related information for custom auth public

  • Dependency injection ; good practices to reduce boilerplate codeAugust 5

    I have a simple question, and I'm not even sure it has an answer but let's try. I'm coding in C++, and using dependancy injection to avoid global state. This works quite well, and I don't run in unexpected/undefined behaviours very often. However I r

Copyright (C) 2017 ceus-now.com, All Rights Reserved. webmaster#ceus-now.com 14 q. 0.765 s.