StructureMap Specifying Explicit Constructor Arguments

I am working on legacy code.

I have different methods of the same class that pass different arguments to the dependency constructor. I am trying to get basic use of IoC. Right now I have a StructureMap passing my arguments as follows:

var thing = ObjectFactory.GetInstance<IThingInterface>(new ExplicitArguments( new Dictionary<string, object> { { "constructorArgA", notShown }, { "constructorArgB", redacted.Property } })); 

If the actual properties passed to constructorArgA and B change depending on where I am.

Instead of "constructorArgA" there is a way to configure this through the actual types, for example, you can do this when setting up an objectFactory, for example:

 x.For<IHidden>().Use<RealType>() .Ctor<IConfig>().Is(new Func<IContext, IConfig>( (context) => someMethodToGetIConfig())); 

If I wrote this from scratch, I would probably have structured the dependencies a little differently to avoid this, but this is not an option for me right now.

+6
source share
1 answer

This is a bit of a classic / general issue with DI containers.

My first choice would be to create a β€œmanual” abstract factory to create the IThingInterface, and then use the Structuremap to inject the IThingInterfaceFactory where necessary. By manual factory, I mean a class that calls the new ThingInterface () and returns it. If you do this like this, your implementation will no longer be managed by the container, and if it has dependencies, they will no longer be provided by the container (it may or may not be a problem for you).

The second choice is to create an abstract factory that actually uses / terminates the container. So, basically your first piece of code, but wrapped up in a factory class, where the Create () method takes your parameters. This has the advantage that everything (including your implementation and its dependencies) is managed by containers, but the disadvantage of directly accessing your container (which is not best practice - see Articles on composition roots ).

You can also do a setter injection, but I personally think this is the last thing.

Windsor Castle has a good solution to this problem ( Typed factory Object ). Not sure if switching containers to an option, but you can consider this.

+3
source

Source: https://habr.com/ru/post/895092/


All Articles