Question

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?

Was it helpful?

Solution

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

OTHER TIPS

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>();

How can this be language-agnostic? This is implementation detail of the framework in question.

Spring alows you to specify c'tor args as a list of values/references, if that's your thing. It's not very readable, though, compared to property injection.

Some people get hot under the collar about this, and insist that c'tor injection is the only thread-safe approach in java. Technically they're correct, but in practice it tends not to matter.

It should not be a very common need, but sometimes it is a valid one. Ninject, which is lighter than StructureMap, allows you to pass parameters when retrieving transient objects from the context. Spring.NET too.

Most of the time, objects declared in an IoC container aren't transient, and accept others non-transient objects through constructors/properties/methods as dependencies.

However, if you really wan't to use the container as a factory, and if you have enough control on the objects you want to resolve, you could use property or method injection even if it sounds less natural and more risky in some way.

Yes, other frameworks are more feature-rich - you need to use an ioc framework that allows for constructor injection. Spring is an example of a multi-language ioc container that allows constructor dependency injection.

Other IoC frameworks are more feature rich.

I.e. check out the ParameterResolution with Autofac

You can also do that with Windsor easily

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