Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass arguments to a constructor in an IOC-framework

How can I pass arguments to a constructor in an IOC-framework? I want to do something like: (Trying to be IOC-framework agnostic ;) )

object objectToLogFor = xxx;
container.Resolve<ILogging>(objectToLogFor); 

public class MyLogging : ILogging
{
    public MyLogging(object objectToLogFor){}
}

It seems that this is not possible in StructureMap. But I would love to see someone prove me wrong.

Are other frameworks more feature-rich? Or am I using the IOC-framework in the wrong way?

like image 575
Ruben Avatar asked Sep 24 '08 19:09

Ruben


2 Answers

In structure map you could achieve this using the With method:

string objectToLogFor = "PolicyName";
ObjectFactory.With<string>(objectToLogFor).GetInstance<ILogging>();

See: http://codebetter.com/blogs/jeremy.miller/archive/2008/09/25/using-structuremap-2-5-to-inject-your-entity-objects-into-services.aspx

like image 54
Edward Wilde Avatar answered Oct 13 '22 23:10

Edward Wilde


For Castle Windsor:

var foo = "foo";
var service = this.container.Resolve<TContract>(new { constructorArg1 = foo });

note the use of an anonymous object to specify constructor arguments.

using StructureMap:

var foo = "foo";
var service = container.With(foo).GetInstance<TContract>();
like image 24
Remco Ros Avatar answered Oct 13 '22 23:10

Remco Ros