Reputation: 9480
I just want to finally wrap my head around static/non-static members for good. I'll be using my ASP.NET MVC 2 + Ninject + Repositories + Providers + Entity Framework application in my examples.
So, assuming that I'm binding a singleton instance of my EF container in the Ninject Kernel, if I have this code, will I see performance improvements, or how exactly will it be affected?
public class Repository<T> where T : class {
// private readonly DefaultContainer = null;
// REPLACED BY:
private static readonly DefaultContainer = null;
[Inject]
public Repository(
DefaultContainer DefaultContainer) {
DefaultContainer = DefaultContainer;
}
}
public class EmployeeRepository {
// private readonly DefaultContainer = null;
// REPLACED BY:
private static readonly DefaultContainer = null;
[Inject]
public EmployeeRepository(
DefaultContainer DefaultContainer) {
DefaultContainer = DefaultContainer;
}
}
In both repositories above I have a private member of DefaultContainer
which is defaulted to null and then injected into the constructor where it's permanently set.
Now, is there a performance improvement if its static over non-static? I ask because reading through MSDN, I read that static members are only allocated once, so does that mean that I can have 20 repositories in a provider and all of them use the exact same DefaultContainer
? Or, does it mean that the first instance of Repository<T>
will allocate DefaultContainer
, but then all subsequent repositories of T
, wherever they are created in the app, will use that DefaultContainer
?
If it's the first option, then wouldn't that increase the performance of the application since there is one object being used by all?
If it's the second option, then wouldn't it also have a performance increase of some kind as well, even if it's allocated once for each Repository<T>
instead of for every Repository<T>
ever?
I'd appreciate someone shedding some light on this to me. I think I get it, but I just need someone to clarify for me.
Upvotes: 0
Views: 92
Reputation: 8390
I recommend doing away with the static members and letting your ioc container manage the lifetime of the object. I recently did a series of blog posts covering much of this same ground. I used nhibernate instead of entity framework. Here is a link that may be of interest:
http://blog.bobcravens.com/category/ninject/
Hope this helps.
Bob
Upvotes: 2
Reputation: 77500
Short answer: no, there is not a performance benefit.
Long answer: By using a static
field, you're blurring whose responsibility it is to maintain the lifestyle of your dependency. Containers like Ninject typically have the option to resolve something as singleton or transient. If you were to decide your repository (and DefaultContainer
) should be transient rather than singleton, but still had the static field, you'd be facing a pretty nasty race condition as the instances successively overwrite the shared field.
Upvotes: 3