smolesen
smolesen

Reputation: 1333

Factory method with string argument

In DryIoc, how do I pass a string argument to a factory method?

In the Wiki, there's an example on how to pass another registered class, but I can't seem to figure out how to pass a string.

Given the following:

public interface MyInterface
{
}

public class MyImplementationA : MyInterface
{
    public MyImplementationA(string value) { }
}

public class Factory
{
    public MyInterface Create(string value)
    {
        return new MyImplementationA(value);
    }
}

public class MyService1
{
    public MyService1(MyInterface implementation) {  }
}

class Program
{
    static void Main(string[] args)
    {
        var c = new Container();
        c.Register<Factory>(Reuse.Singleton);
        c.Register<MyInterface>(Reuse.Singleton, made: Made.Of(r => ServiceInfo.Of<Factory>(),
            f => f.Create("some value") //How do I pass a string to the factory method?
        ));

        c.Register<MyService1>();

        var a = c.Resolve<MyService1>();
    }
}

Upvotes: 2

Views: 1267

Answers (1)

dadhi
dadhi

Reputation: 4950

If you want to inject a string value for specific dependency you can do it like this:

c.Register<Factory>(Reuse.Singleton);
c.Register<MyInterface>(Reuse.Singleton, 
    made: Made.Of(r => ServiceInfo.Of<Factory>(),
           // Arg.Index(0) is a placeholder for value, like {0} in string.Format("{0}", "blah")
            f => f.Create(Arg.Index<string>(0)), 
            requestIgnored => "blah or something else"));

Here the similar example from the wiki on how to provide Consumer type to log4net logger.

Another way is c.RegisterInstance("value of blah", serviceKey: ConfigKeys.Blah);.

Or you can use FactoryMethod registration to register string provider, to get calculated, lazy, or whatever value. Example with attributed registration for clarity:

[Export, AsFactory]
public class Config
{
    [Export("config.blah")]
    public string GetBlah()
    { 
      // retrieve value and
      return result;    
    }
}

// In composition root:
using DryIoc.MefAttributedModel;
// ...
var c = new Container().WithAttributedModel();
c.RegisterExports(typeof(Config), /* other exports */);

Upvotes: 2

Related Questions