Question

I'm trying to build my own inversion of control container. Right now I store the objects with their types in a dictionary and resolve a reference when asked. But I want to make it possible to resolve a reference or a new instance. I can create a new instance with the Activator class. But, what if the constructor of the object to resolve takes 1, 2 or any parameters?

For example, I want to be able to say something like:

Container.register<IFoo>(new Foo(Proxy));
Container.register<IBar>(new Boo(Proxy, DataThing));

and resolve it like

IFoo MyFoo = Resolver.resolve<IFoo>();
IBar MyBar = Resolver.resolve<IBar>();

where MyFoo gets instanciated with the given parameter Proxy and MyBar with Proxy and DataThing.

What does resolve have to do to make that happen?

Was it helpful?

Solution 2

I decided to split it in to methods. A Resolve, that gives back the instance stored in the container. And a Create that instanciate a new instance.

something like:

 public T Create<T>()
         {
             if (registeredTypes.ContainsKey(typeof(T)))
                 return (T)Activator.CreateInstance(registeredTypes[typeof(T)].
                                                                       GetType());
             else
                 throw new DependencyResolverException("Can't
                                       create type. Type " + typeof(T) + "
                                                           not found.");
         }

OTHER TIPS

Checkout http://funq.codeplex.com. This is a very tiny Container that uses lambda expressions to define the function to resolve. Handles multiple parameters.

Activator can create an instance of a class having constructors with parameters.

Have a look at this overload of CreateInstance method.

You can provide a custom binder to search for matching constructor manually.

In your case resolve method should return reference to an instance of registered class (new Boo(Proxy, DataThing) in your example)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top