Sorskoot
Sorskoot

Reputation: 10310

How to resolve instances with constructor parameters in custom IOC Container?

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?

Upvotes: 0

Views: 2741

Answers (3)

Matthew
Matthew

Reputation: 2072

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

Upvotes: 2

Sorskoot
Sorskoot

Reputation: 10310

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.");
         }

Upvotes: 1

aku
aku

Reputation: 123974

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)

Upvotes: 0

Related Questions