0

I have multiple projects in my MVC solution.In my web project ImageController has the update,delete and create methods for all the Image classes in my project. At the moment I'm using switch options to access relevant services from service layer (another class library project).

namespace MySolution.Web.Controllers
{
    public class ImageController : Controller
    {
      public void UpdateMainImage( string imageClassName, string name, long id)
      {
          using (ServiceFactory factory = new ServiceFactory())
            {
                switch (imageClassName)
                {
                    case "CategoryImage": factory.CategoryImage.UpdateDisplayImage(name, id);
                        break;
                    case "ItemImage": factory.ItemImage..UpdateDisplayImage(name, id));
                        break;
                  //other case statements                                                   
                }
      }

// Delete Image Method
public void DeleteImage( string imageClassName, long id)
      {
          using (ServiceFactory factory = new ServiceFactory())
            {
                switch (imageClassName)
                {
                    case "CategoryImage": factory.CategoryImage.DeleteImage( id);
                        break;
                    case "ItemImage": factory.ItemImage..DeleteImage(id));
                        break;
                  //other case statements                                                   
                }
      }
    }

Can I select the relevant Imageservice class dynamically? The imageClassName variable contains the Image service class name.

factory.imageClassName.DeleteImage(name, id);

Is there a way to use a string variable to replace the Class name?

  • `Reflection` can do this, but it's slow and complicated. I suggest you to use switch statement. – opewix Dec 19 '14 at 04:53
  • @JesseJames thanks for the quick reply. Yes I saw few answers and posts using Reflection. http://stackoverflow.com/questions/1044455/c-sharp-reflection-how-to-get-class-reference-from-string Though I have to write more codes ,it's better to use switch statement if there is no other better solution. – user3627847 Dec 19 '14 at 05:09

1 Answers1

0

Are your classes (CategoryImage, ItemImage, etc.) inherited from the single interface or the abstract class?

You can use Dictionary<string, ImageService in this case, where ImageService is base class or interface.

private static IDictionary<string, ImageService> imageServices = new Dictionary<string, ImageService>
{
    { "CreateImage", new CreateImage() },
    { "ItemImage", new ItemImage() },
};

// somewhere below:
imageServices[imageClassName].UpdateDisplayImage(name, id);
Mark Shevchenko
  • 7,937
  • 1
  • 25
  • 29