As some other folks have mentioned, prefer constructor injection. This will solve many of your problems.
If your classes have direct dependencies on the IoC container itself, it tends to be a variant of using the service locator (anti-)pattern. In this particular case, isolate which types are being resolved via the service locator, and abstract that dynamic resolution with a factory interface. So, for instance, replace this:
public class Foo
{
private MyIoCContainer _container;
public Foo(MyIoCContainer container)
{
this._container = container;
}
public void DoSomething()
{
// have to do this at runtime for whatever reason
var myObj = this._container.Resolve<ISomeType>();
myObj.DoSomething();
myObj.DoSomethingElse();
}
}
with this:
public class Foo
{
private IObjFactory _provider;
public Foo(IObjFactory _provider)
{
this._provider = provider;
}
public void DoSomething()
{
var myObj = _provider.GetObj();
myObj.DoSomething();
myObj.DoSomethingElse();
}
}
public interface IObjFactory
{
ISomeType GetObj();
}
Now, you have an IObjFactory
that can encapsulate the dynamic, runtime nature of constructing objects that implement ISomeType
. If you are constructing many different types of object from the container/service locator, then you should have at least as many *Factory
interfaces (in accordance with the Interface Segregation Principle).