Web API, DI and object lifetime via nested containers? - dependency-injection

OK, I wired up StructureMap to my Web Api application (plenty of samples how to do this here on StackOverflow and elsewhere on the Internet). My understanding of object lifetime maintenance in Web Api is that it's done via nested containers.
For the whole idea of object lifetime maintenance via nested containers to work, Raven's session object would have to be created in child container as a transient singleton. Right now I have IDocumentStore defined in in parent container and scoped as singleton. IDocumentSession is also defined in parent container but scoped as HttpContext. When request comes in, BeginScope() is called, nested container is created but IDocumentSession object in it is inherited from the parent instead of being created.
I don't understand how this is supposed to work. If object is not created in child container as a transient singleton but is inherited from the parent instead then it will go back to the parent when nested container is disposed. This then defeats the whole idea. If on the other hand session is to be created in nested container as a transient singleton then how this can be accomplished? How can I verify the correctness of such setup?

If I set IDocumentSession as Per Web Request then why the need for
nested containers in the first place?
There is no need for nested containers in that scenario.
The need for nested containers by itself in general is even doubtful. Even the designer of Castle Windsor (a container that supports child containers) is considering to remove support for child containers in the next version of Castle Windsor all together.

Related

Dependency injection - Instance Lifetime for .Net MVC 5 webapps - Unity Container

I'm trying to have a better understanding of the lifetime of objects in DI by the point of view of an webapp. I'm using Unity Container docs here.
Singleton
Singleton lifetime creates globally unique singleton. Any Unity
container tree (parent and all the children) is guaranteed to have
only one global singleton for the registered type.
Now, because I've read so many articles, I've come to understand that Singleton is a instance that is created once and used for the entire life of application. What does this mean having in mind that 2 users use my app in the same time(or not) from different PCs - does this mean that if this instance is a variable, it will be common for all users for the entire time my app is hosted on the server (or until app App Pool Recycle)?
In my app I use different services that are injected in the controllers constructor.
Will Singleton be suited for an instance of a log service, or a DbContext instance?
If I use it for a DbContext instance, and something get's modified in the my Db structure - this instance will update?
Per Container
Per Container lifetime allows a registration of an existing or
resolved object as a scoped singleton in the container it was created
or registered. In other words this instance is unique within the
container it was registered with. Child or parent containers could
have their own instances registered for the same contract.
Same case: If 2 users use my app in the same time and visit same Controller, does this mean that they share the same instance of a Per Container variable/service?
Hope these questions have some meaning and I don't simply overthink it. Thank you!

ASP.NET MVC dependency injection outside the controller with Unity

I am building an ASP.NET MVC 5 application using the repository and service layer design patterns. I have used unity to inject my services into my controllers.
This works nicely and until now I have not had a need to consider instantiating any objects requiring injection of interfaces outside my controllers. However I have a need for this when configuring my application startup to setup some users in the database.
For this I wanted to user my UsersService that I've built. And it occurred to me as the application grows there will surely be other occasions when I'll want to do the same, such as calling a service from within another service.
I see that I can instantiate a Unity container and call resolve on it to get my new instance of a service:
IProductService productService = container.Resolve<IProductService>();
However this kinda smells to me, having the container leaked all over my application seems like an anti pattern. So is there a better way to do this?
Unity and other dependency injection containers automatically do this. When you inject a service into a controller, it will automatically resolve the entire dependency graph of that service. Not only can you resolve dependencies of the service and its dependencies, you should inject dependencies into the service that needs them instead of the controller.
Any class (including the controller) that has more than a handful of dependencies is a code smell that you are violating the Single Responsibility Principle, and you most likely should refactor to aggregate services.
And yes, injecting the container to any point outside of the composition root is an anti-pattern called a service locator.
As for injecting services outside of the controller, it is important to distinguish between injectables and runtime data. For example, some try to inject services into DTO objects, attributes, static classes/extension methods, and other places where it is anti-pattern for services to be injected. For these situations, it is important to properly assess the situation and refactor toward a DI-friendly solution - favoring constructor injection over other alternatives and considering a service locator as a last resort. For example, if you are trying to make an extension method with a dependent service, most likely you have some functionality that itself should be a non-static service, DTOs should never be created from a DI container, and you may have to make use of more than one extension point in MVC where you inject the container within the composition root of the application, which does not constitute a service locator.
Is it worth it? Usually. What is gained? You gain the ability to change the application much more quickly than if you have a tightly-coupled application in ways that the designer of the application may not have even anticipated. So the extra cost of ensuring the application is loosely-coupled is usually more than recouped in ongoing maintenance of the project. As a side benefit, you gain the ability to easily unit-test each component independent of the others.

Injecting Stateful Bean inside Stateless bean

When injecting a stateful session bean inside a stateless session bean using DI, what happens exactly:
Did the container inject a new instance of stateful bean for every stateless bean (which exists in a pool), or it is the same instance shared between them?
Why it is indicated that using JNDI in this case is better than DI?
I really didn't get that.
Basically it doesn't make sense to inject stateful into stateless, because that stateful will be shared by many clients, if they happen to get same stateless instance, or one client can also access different stateful instances, if it access different stateless instances.
Using JNDI or not, doesn't make any difference in this case. Stateful cannot be shared by many clients and each statelss instance is a different client. If you will use JNDI then depending where you do the lookup you can end up with new stateful instance with every call to the stateless.
Any reason why would you like to inject stateful in stateless?
For each session the #Statefull will be new instance.
#Statefull isn't a direct instance, it's a proxy and can be changed every time when is needed even inside #Stateless

How do I get Unity to inject a reference to HttpSessionState to a service

Disclaimer: I have a fair bit of experience with DI containers but am quite new to Unity.
I have an MVC project that is all wired up with Unity DI using constructor injection and works great. But I now have a service that I want to inject into my controllers (and maybe places other than controllers at some point) and this service needs access to ASP.NET session state. The service's purpose is to manage a list in session and I don't want the list mechanics in my controller.
I realize I could add a Setup method to the service (and it's interface) that my controller could call, passing in a reference to the Session, before using the service, but I don't like that as I may want to make an implementation of the service that uses something other than Session for my state management and also it is implementation specifics leaking into my interface. I also realize I can use HttpContext.Current in my service but I don't want to do that for many reasons, particularly for the issues it creates for unit testing.
Can Unity inject a reference to HttpSessionState into the service's constructor?
There's a couple ways to do this. The easiest is probably to use an injection factory:
container.RegisterType<HttpSessionState>(
new InjectionFactory(c => { return HttpContext.Current.Session; }));
Then anywhere you have a dependency on the HttpSessionState in the graph, the delegate given will run and pull it out of HttpContext.Current.
Of course, this only works if you're doing a new resolve per request.

Dependency Injection Of Model Repository - Is It A Singleton?

My controllers now implement an interface and inject a repository implementation using the Unity framework. My question is, are these injected implementations singletons? Does that mean all of my users hitting the repository (from the controller) use the same instance?
It depends on whether you carry some ORM session along with your repository instance. If your repository is just a bunch of static methods than you shouldn't care and you can make it a singleton. Otherwise you want to preserve the state only within one web request so that other requests threads don't interfere with it.
Unity, unlike other IoC frameworks. doesn't come with singleton per web request lifetime manager, but you can easily implement it, see here for instance:
Singleton Per Call Context (Web Request) in Unity
No, do not make repositories singleton, special in a web application.
The controller factory create the repository (using Unity) and inject them in the controller.
Taken from the MSDN Unity docs...
The lifetime of the object it builds will correspond to the lifetime you specify in the parameters of the method. If you do not specify a value for the lifetime, the type is registered for a transient lifetime, which means that a new instance will be created on each call to Resolve...
Include an instance of the ContainerControlledLifetimeManager class in the parameters to the RegisterType method to instruct the container to register a singleton mapping.
So basically, the injection is transient unless you specify it as a singleton.

Resources