I am trying to solve an IoC problem that at first seemed easy, but turned out to be a pain in the ass: -P
I have a main heavy weight class that needs to be initialized only once, so it is marked as Singleton. However, this class uses a subclass that must be created once for each request, so it is marked as Transient:
public class MyRegistry : Registry { public MyRegistry() { For<IMainClass>() .Singleton() .Use(ctx => new MainClass(() => ctx.GetInstance<ISubClass>())); For<ISubClass>() .Transient() .Use(ctx => CreateNewInstanceOfSubClass()); } private ISubClass CreateNewInstanceOfSubClass() { return new SubClass(); } } public interface ISubClass { } public class SubClass : ISubClass { } public interface IMainClass { } public class MainClass : IMainClass { private readonly Func<ISubClass> _subClassProvider; public MainClass(Func<ISubClass> subClassProvider) { _subClassProvider = subClassProvider; } public void DoStuff() { var requestSpecificInstanceOfSubClass = _subClassProvider();
As you can see, I pass lambda to the MainClass constructor, which is used to get the ISubClass instance. During debugging, I could definitely see that ctx.GetInstance<ISubClass>() is executed every time MainClass needs an instance of SubClass . But, to my surprise, SubClass is created only once, as a single, instead of creating for each request.
However, when I call container.GetInstance<ISubClass>() directly from somewhere inside my code, the behavior is exactly what I wanted. SubClass is created once and only once for each request.
I'm not quite sure, but I think the problem arises from the context object that is passed the lambda, which is the singleton (?) Context. But I really don't know how to get the desired behavior here!
I hope you help me with this. Thank you for your responses.
Regards, Dante
c # dependency-injection ioc-container structuremap
dante
source share