Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass dynamic arguments to Structuremap when constructing a new type?

There are cases in my app where my repositories require passing different arguments to constructors of the concrete types. I want to be able to do something like this:

var arg = (x == y) ? z : a;
ObjectFactory.GetInstance<IRepository>(arg);

Where the argument can only be constructed at the time of creating the Repository instance depending on some condition.

How can this be done?

like image 773
Roman Avatar asked Jan 20 '23 10:01

Roman


2 Answers

As @Steven also says, I think that if possible you should let the class that needs the dependency (that has a dynamic argument) take a factory as a parameter so that you can control the creation from the consumer.

With structure map there is built in support for this so that you don't have build a factory class.

Let the consumer take a Func as a ctor argument and create the repository (dependency) by invoking the Func with the argument:

public class Consumer
{
    public Consumer(Func<ArgumentType, IRepository> repositoryFactory)
    {
      _repositoryFactory = repositoryFactory;
    }

    public void CallRepository()
    {
       ArgumentType arg = (x == y) ? z : a;
       var repository = _repositoryFactory(arg);
       repository.GetById(...);
    }
}

In the configuration for structure map, you can configure the func:

For<Func<ArgumentType, IRepository>>().Use( arg => new Repository(arg));
like image 81
PHeiberg Avatar answered Jan 22 '23 21:01

PHeiberg


I think something like this should work:

var arg = (x == y) ? z : a;
ObjectFactory.With("argumentName").EqualTo(arg).GetInstance<IRepository>();
like image 34
gram Avatar answered Jan 22 '23 19:01

gram