Mapping between T & # 8594; IHandler <T>

I have the following interface

public interface IHandler<T> { void Handle(T myObject); } 

I would like to have a HandlersManager class that contains a mapping of object types to the corresponding handler, but I'm not sure how I should define an object that holds this mapping.

For example, I would like to have the following:

 typeof(string) --> instance of IHandler<string> typeof(MyClass) --> instance of IHandler<MyClass> 

The best I have received so far is to define a Dictionary<Type, object> for matching, but in this case I would have to pass an IHandler<T> value every time I get it.

Is there a better solution or something that I completely missed?

+7
source share
2 answers

This is as good as you can get with only the common IHandler<T> interface.

To examine additional parameters, we could define a non-generic version of the interface:

 public interface IHandler { void Handler(object myObject); } 

Then you can also define a generic abstract base class that implements both IHandler<T> and IHandler :

 public abstract class BaseHandler<T> : IHandler, IHandler<T> { public abstract void Handle(T myObject); void IHandler.Handle(object myObject) { ((IHandler<T>)this).Handle((T) myObject); } } 

At this point, you can have an IDictionary<Type, IHandler> , and you can directly call IHandler.Handle on the values ​​you pull from it:

 var obj = /* whatever */ dictionary[obj.GetType()].Handle(obj); 

On the other hand, we now have an additional interface and an abstract base class to hide the cast from the "user" code, which is not very impressive.

+5
source

I suspect you are using this to resolve dependencies. Instead, use a special container that will handle these problems for you.

If you do not want to do this, you need something like this:

 Dictionary<Type, object> dictionary; IHandler<T> Resolve<T>() { return (IHandler<T>)dictionary[typeof(T)]; } 

There are no other ways with generics.

Is there a better solution or something that I completely missed?

No, but manager classes tend to smell like code. Be careful.

+10
source

All Articles