Most appropriate Lifetime Manager for Controller? - asp.net

Currently I'm using Microsoft.Practices.Unity.HierarchicalLifetimeManager as the lifetime manager for my controllers because it calls dispose on the objects it contains. However, it seems that I'm running into cross-threading issues now (multiple request variables are getting mixed up). Reading further into the lifetime manager, it implements a Singleton pattern, which I believe is my problem.
I'm using Unity 2.1. Can any recommend the most appropriate lifetime manager to use with ASP.net MVC controllers, that will call dispose on each of its contained objects at the end of each request?
Thanks so much.

I would think any here that don't implement as a singleton should work. You'll need to pick the best for your needs. PerThreadLifetimeManager sounds pretty good, although it doesn't call Dispose. However, it will be garbage collected when the thread dies.

Related

ASP.NET DbContext instance injection but not used - performance issue or not?

Latest approach says about injecting DbContext instance right to the MVC\WebAPI controller. It has a number of pros but I have one question which is not answered yet - performance of the DbContext instance creation which will not be used.
According to this question: What happens when i instantiate a class derived from EF DbContext? DbContext creation is not so cheap operation (both memory and CPU). And it's twice bad when:
Your action doesn't need the DbContext at all (so you have a mix actions which use and not use the DB)
Some logic (e.g. conditions) doesn't allow to access the DbContext (e.q. ModelState.IsValid). So action will return result BEFORE access to the DbContext instance.
So in both (an maybe some other cases) DI creates a scoped instance of the DbContext, wastes resources on it and then just collect it at the end of the request.
I didn't make any performance tests, just googled for some articles firsts. I don't say that it will be 100% lack of the performance. I just thought: "hey man, why have you created the instance of the object if I will not use it at all".
Why have you created the instance of the object if I will not use it
at all.
Mark Seemann said in his book Dependency Injection in .NET, "creating an object instance is something the .Net Framework does extremely fast. any performance bottleneck your application may have will appear in other place, so don't worry about it."
Please note that Dbcontext enables lazy loading by default. Just by instantiating it, it doesn't have much impact on the performance. So, I would not worry about Dbcontext.
However, if you have some custom classes doing heavy lifting inside constructor, then you might want to consider refactoring those.
If you really want to compare the performance, you could wrap those dependencies with Lazy, and see how much performance you gain. Does .net core dependency injection support Lazy.
You could register it as Lazy or you could do what I do and just inject IMyDbContextFactory and then you can call Create() that will return the DbContext when you actually need it (with its own pros/cons). If the constructor doesn't do anything, it won't be a huge hit, but keep in mind that the first time it gets newed up, it will hit the static constructor that goes through and does all the model validation. This hit only happens once, but it is a huge hit.

ASP.NET thread agility - how to overcome?

ASP.NET is known to exhibit what is called "thread agility". In short, it means that multiple threads may be employed to fulfill a single request, although not more than one thread at a time. This is an optimization that means a thread waiting for asynchronous I/O may be returned to the pool and used to service other requests.
However, ASP.NET does not migrate all thread-related data when moving a request. Microsoft either forgot to do so, or thought that using thread-local storage (made easy by the ThreadStatic attribute) was something only the people coding ASP.NET themselves should do.
Based on quick googling, it seems to me that the only way to avoid the issue is to rely on HttpContext instead. The context is indeed migrated if ASP.NET decides to switch threads mid-request, so this overcomes the problem. But it creates a brand new headache instead: It ties your application logic to HttpContext, and therefore to a web context. That's not acceptable in all situations (in fact, I'd say it's unacceptable in most). Besides, since HttpContext is sealed and has internal constructors, you cannot mock or stub it, and therefore your logic also becomes untestable.
According to this (old) blog post, CallContext does NOT work, which is pretty infuriating given that a call context is conceptually precisely a logical thread!
Is there a simple way to reliably implement "per-LOGICAL-thread" isolation that will work in asp.net contexts as well as other contexts?
If not, does anyone know of a lightweight third-party framework that solves the problem? Does StructureMap behave correctly when ASP.NET migrates threads?
I would like a general answer, but in case anyone wonders, the specific use case I'm looking at is for use of Entity Framework in a SharePoint context. We're unfortunately stuck with SP-2010 and EF 3.5 for a while. EF basically requires that data is saved using the same context as they were originally read from - or else you have to keep track of changes yourself. I would like to introduce a "current model" concept. The first time the model is called upon in processing each HTTP request it should be instantiated, and then that same model instance should be used for the duration of the request. But the code relying on "Model.Current" should also work if executed in the context of a timer job. I'm fine with the timer job code explicitly disposing of the model when done with it (a task I'd like to give to a handler for HttpApplication.EndRequest in the SharePoint web context).
There may be reasons not to do this, and that's interesting too, but I would anyway really appreciate to learn of a way to achieve "logical thread isolation" in an asp.net context, as it'd be remarkably useful.
There is a nice post related to the problem: Implicit Async Context ("AsyncLocal").
If I got everything right, Logical CallContext i.e. CallContext.LogicalGetData and CallContext.LogicalSetData make it real to migrate immutable data correctly given you live in the world past .NET 4.5. This immutable limitation is a nut but still...way to go.

What is Unity's equivalent of Windsor's Release

I have some unmanaged resources in classes I'm injecting into controllers that I need to dispose once the controller is disposed (otherwise I'll have memory leak). I have looked at IUnityContainer and did not find a Release (or similar) method that allow me to do that.
After some trial and error (and reading), it seems to me that Unity do not keep track of what is going on about the types it creates. This is way different from Windsor, where I can call Release and the entire object graph will be release. This is actually one of the points of having a container in the first place (object lifecycle management). I should not need to call Dispose directly the container should be able to do that for me in the proper order/objects.
So, my question is, how can I tell Unity that an object is no longer needed and should be disposed?
If there is no way of doing that, is there a way to change the lifecycle to per web request?
As a note, changing the container is not an option. Unfortunately :(
You will have to look at the different lifetime managers in Unity. The ContainerControlledLifetimeManager will call dispose on every item it creates. Unfortunately this manager acts as a singleton for resolved objects so might not be appropriate for you.
The other alternative is to create your own lifetime manager which keeps track of objects that it creates and when the container is disposed just disposes every object.

NHibernate, Sqlite, missing tables and IOC fun

I'm doing unit testing on a class library that uses NHibernate for persistence. NHibernate is using a Sqlite in-memory database for testing purposes. Under normal circumstances, it's easy to get StructureMap to kick out a session for me.
However, because I'm using the in-memory database to improve testing speed, I need to have a single session available for the duration of a test (because it blows the database away when I create a new one). And there is another wrinkle. The case that is currently burning me is testing a custom NHibernate-based ASP.NET membership provider. These are created apparently once per AppDomain, so I shouldn't inject the session into it, for obvious reasons.
Is there a way in structuremap to tell it to get rid of an instance of a particular type while still maintaining the bits that tell it how to instantiate that type? Really, if I could get away with it, I would just make it act like the HttpScoped object lifetime, but apparently I can only do that within the context of an Http request. Is there a straightforward way to manually control the lifetime of an object coming out of structuremap?
I apologize for the length of this and the possibility that it is a dumb question. I'm solo on this project, so I don't really have anyone to bounce ideas off of.
You could wrap the session in your own ISession implementation which delegates to a real session which lifetime you control. Then register your own ISession as instance.
I ended up making two constructors for my provider along with a private variable of type Func. By default, its value was set to my standard code for creating a session using StructureMap's ObjectFactory.
The overloaded constructor accepted as a parameter an object of type Func. That way, I can inject a strategy for creating an instance of that type if needed, but otherwise don't have to go through any extended effort. In the case of my test, I created the session in the NUnit setup method and destroyed it in the Teardown. I don't love this idea, but I don't currently hate it enough to rip it out....yet.
This got rid of the error I was experiencing in regard to the tables. However, it appears that NHibernate for some reason cannot write to an in-memory sqlite database under the conditions I created. I'm now working on testing to see if I can write to one in the file system. It isn't ideal, but it will be a good long while (I hope), before the performance of writing to disk really starts hurting.

Should the composition root be transient or per-request when using ASP.NET with Castle Windsor?

Following the suggestion in "Dependency Injection in .NET", I am resolving the composition root in each page constructor like this:
public MyPageConstructor()
{
var container = (Castle.Windsor.WindsorContainer)HttpContext.Current.Application["DIcontainer"];
Controller = container.Resolve<MyPageController>();
}
Now, if I make the controller transient, I have to release it manually when the page is unloaded. If I make it per-request, Castle will release it for me when the request is over but there may be a performance penalty, I am not sure. At the moment I tend to make the objects transient and handle the release on my own.
Are there other things to consider and what would be the recommended practice?
Thank you.
I recommend to use the longest possible lifetime. Unfortunately, complex application can have more than one entry points, where the Resolve method has called. And if you chose Transient, there is a risk that some service would be created multiple times per request. For example, some HttpModule could use the same services, as a Page. With PerRequest lifetime such issue can be avoided.
It depends, if you have a class that has a lot of dependencies on it, the overhead of instantiating the same thing over and over, might be to severe. But if have something that isn't threadsafe you are better of as transient.

Resources