user1492051
user1492051

Reputation: 906

Avoiding reflection

I have 81 classes(still growing) which implement an interface, and I have a class that has a property that represents that interface ex:

public wrapper
{
   public Imyinterface instance{get;set;}

   public wrapper(string theNameOfTheClass)
   {
    instance = System.Reflection.Assembly.GetExecutingAssembly().CreateInstance(theNameOfTheClass);
    instance.Run(); //the interface has a run method
   }
}

is this the best way to go with, and how can I avoid reflection and not have to write any extra code?

Upvotes: 0

Views: 635

Answers (2)

Spook
Spook

Reputation: 25927

I'm not sure, but maybe:

public Wrapper<T>
   where T : IMyInterface, new()
{
    public IMyInstance instance { get; set; }

    public Wrapper()
    {
        instance = new T();
        instance.Run();
    }
}

Use it like:

Wrapper<SomeClass> wrapper = new Wrapper<SomeClass>();

If you want to keep the wrappers on some kind of list, simply derive them from common, non-generic class:

public abstract class BaseWrapper
{

}

public class Wrapper<T> : BaseWrapper
...

Edit: In response to comments

Maybe the problem is not in the wrapper class. If you get a string from user, you have only two options: either a giant switch or reflection.

You may change that for example by changing the ListBox contents:

public class ComboBoxItem
{
    public string Title { get; set; }
    public Func<IMyInterface> creator { get; set; }        

    public override string ToString()
    {
        return Title;
    }
}

Now create a list of these items and pass it to the ComboBox:

var items = new[] {
    new ComboBoxItem { Title = "First class", creator = () => new FirstClass() },
    new ComboBoxItem { Title = "Second class", creator = () => new SecondClass() },
}

You have to populate that ComboBox anyway, so there will be some hardcoding. The point is to hardcode the class list only in one place (maybe even in a place unrelated to the ComboBox, and then re-create ComboBox contents basing on that list).

Upvotes: 4

Michal Ciechan
Michal Ciechan

Reputation: 13888

Have a look at Unity IoC (or any other IoC that can resolve from string):

From IOC Container Runtime Resolution

string typeName = "MyTypeName";
var type = container.Registrations.FirstOrDefault(r => r.RegisteredType.Name == typeName);
if(type != null)
{
    var resolvedInstance = container.Resolve(type.RegisteredType);
}

EDIT: For Convention over Configuration have a look at the links at links in this question

Using Unity With Minimal Configuration

Upvotes: 1

Related Questions