BanksySan
BanksySan

Reputation: 28500

Calling a factory to return a type with Unity IoC

I have a factory:

public class FooFactory : IFooFactory
{
    public IFoo CreateFoo(IBar bar)
    {
        return new Foo(bar);
    }
}

My Unity container needds to get a resolve a Foo.

var container = new UnityContainer();

container.RegisterType<IBar, Bar>();
conatiner.RegisterType<IFooFactory,FooFactory>(
    new InjectionConstructor(new ResolvedParameter<IBar>())
container.RegisterType<IFoo, Foo>(????????);  //What should be here?

How do I tell Unity to call the method on the Factory in order to get an IFoo?

Upvotes: 0

Views: 253

Answers (2)

matt
matt

Reputation: 9401

I think you're trying to over-engineer this - You have a class (FooFactory) that:

  • When given an IBar instance,
  • Returns an IFoo instance

Use the factory to generate your IFoo instances:

public class Greeter
{
  private readonly IFooFactory _fooFactory;

  public Greeter(IFooFactory fooFactory)
  {
    _fooFactory = fooFactory;
  }

  public string SayHelloWithABar(IBar bar)
  {
    IFoo foo = _fooFactory.CreateFoo(bar);

    // do something with your 'foo' instance ...

    return "hello!";
  }
}

Upvotes: 1

jgauffin
jgauffin

Reputation: 101130

You could do it using an InjectionFactory. I do however recommend you switch to use the IFooFactory as a dependency in Bar. It makes the code easier to follow.

Better:

public class Bar
{
    private IFoo _foo;

    public Bar(IFooFactory fooFactory)
    {
        _foo = fooFactory.Create(this);
    }
}

Upvotes: 0

Related Questions