Search code examples
c#dependency-injectionunity-container

Using Unity, How should I Pass a "Model" to a Resolved Type?


I've got an interface, which we'll call IFoo, for argument's sake, that works with files. The implementation of this interface receives a FileInfo in its constructor. In my bootstrapper, I have it set up like this:

container.RegisterType<IFoo, Foo>();

The problem is that I don't know which FileInfo I need to pass into the Foo instance until it is resolved. I'll have one, and I need to pass it into the constructor.

I've seen older posts that recommend using a parameter override and the use of container.Resolve, but I understand that this is generally a bad practice.

Is there a recommended approach for achieving what I need to do?

TLDR: I need to be able to do something like this, that isn't frowned upon:

container.Resolve<IFoo>(*pass my constructor arg here*)

Solution

  • The problem is that I don't know which FileInfo I need to pass into the Foo instance until it is resolved.

    This implies that FileInfo is runtime data, while your application components (your Foo) should not require runtime data during construction.

    Please read this article for a detailed discussion on why runtime data is bad, and which solutions there are.