Recently I noticed my application appears to be eating memory that never gets released. After profiling with CLRProfiler I've found that the Castle Windsor container I'm using is holding onto objects. These objects are declared with the lifestyle="transient" attribute in the config xml.
I've found if I put an explicit call to IWindsorContainer.Release(hangingObject), that it will drop its references.
This is causing a problem though, I wasn't expecting that with a transient lifestyle object CastleWindsor would keep a reference and effectively create a leak. It's going to be a rather mundane and error prone task going around inserting explicit Release calls in all the appropriate places.
Have you seen this problem, and do you have any suggestions for how to get around it?
I think the answers here are missing a vital point - that this behavior is configurable out of the box via release policies - check out the documentation on the castle project site here.
In many scenarios especially where your container exists for the lifetime of the hosting application, and where transient components really don't need to be tracked (because you're handling disposal in your calling code or component that's been injected with the service) then you can just set the release policy to the NoTrackingReleasePolicy implementation and be done with it.
Prior to Castle v 1.0 I believe Component Burden will be implemented/introduced - which will help alleviate some of these issues as well around disposal of injected dependencies etc.
Edit:
Check out the following posts for more discussion of component burden.
The Component Burden - Davy Brions
Also component burden is implemented in the official 2.0 release of the Windsor Container.
One thing to note is that this seems to have been fixed in the Castle Trunk. In r5475, Hammett changed the default release policy in MicroKernel to LifecycledComponentsReleasePolicy.
You can set a lifestyle of singleton or transient though on objects in the container. Singleton objects I understand should last the life of the application, but I don't understand the usefulness of this behvaviour being the same for transient ones!
Custom lifestyles can be created by implementing ILifestyleManager. Maybe it's possible to implement this suitably to create a ReallyTransient lifestyle type!
Related
From Using the Simple Injector in Simple Injector documentation:
Note: Calling the GetInstance method in the constructor is suboptimal and should be avoided whenever possible. With ASP.NET Web Forms however, it is hard to completely avoid this. Please see the Integration Guide for alternatives.
Why exactly is it suboptimal?
I did notice that this kind of usage can cause issues due to the intentional limitation that the container is locked after the first call to resolve. Thus if you register A, then create a collection of ISomething - one of which has a dependency on A - and then you register that collection using RegisterAll(), then you run into trouble because one of the ISomethings resolves A, preventing the subsequent registration of the collection.
However I imagine there is more to "suboptimal" than this.
Calling back into the container from within the constructor of your type is sub optional, because:
You render your DI library blind, and disallow it to see which dependencies a type has, which makes it impossible to warn you about any misconfigurations you might have made.
Makes it impossible for the DI library to optimize the object graph construction for you.
Makes it impossible to apply features such as Context Based Injection that work by changing the expression tree before it gets compiled to code.
You make it harder to unit test code that calls into the container.
Calling back into the container is an anti-pattern called Service Locator.
Unfortunately, the documentation you are pointing at is a bit outdated and in general we advice against using this type of construct. The ASP.NET Web Forms Integration page therefore describes a better solution for this using explicit property injection.
I'm coming from a background with Java and Spring, and I am rather new with Castle Windsor. I've read that it is important to know when transient components will be released by Castle since it tracks all components created. I'm having a hard time understanding when my components will be released though. Here is the basics of my model:
Singleton -> Singleton Typed Factory -> Transient Objects
If I release the first singleton in this chain will all the transient objects created by the typed factory be released? Is there any API call I can make to check if this is the case? I can't find any comprehensive API documentation on the Castle Windsor website. The documentation I did find just doesn't seem clear to me.
Edit:
My problem boils down to two main questions.
If I have a singleton object (A) that depends on a singleton typed factory (B) and I release singleton A will that actually release B? The blog post mentioned in the answer below says that calls to release on singleton objects are ignored, so my assumption is no it will not be released.
If I have a singleton typed factory that is used by multiple web requests simultaneously to create transient objects and is released by one of the web requests, will all the transient objects be released, whether they were created from that web request or not? It almost seems like making typed factories per web request or transient lifestyle is better.
Here's a detailed post that explains how Windsor tracks objects and when you need to call Release: http://kozmic.pl/2010/08/27/must-i-release-everything-when-using-windsor/
Updates to your updates
Any release on a singleton is ignored so, yes, you're correct -- it will not be released.
You only need to worry about Releasing components you specifically resolved. If it was resolved by Windsor (via Typed Factory Facility, sub-dependency resolver, etc...) don't worry about it.
I have a project where the Ninject is used as IoC container. My concern is that a lot of classes have such kind of constructors:
[Inject]
public HomeController(
UserManager userManager, RoleManager roleManager, BlahblahManager blahblahManager) {
_userManager = userManager;
_roleManager = roleManager;
_blahblahManager = blahblahManager;
}
What if I don't want to have all instances of these classes at once?
The way, when all this classes are wrapped by Lazy<T> and passed to constructor is not exactly what I need. The T instances are not created yet, but Lazy<T> instances are already stored in memory.
My colleague is suggesting me to use Factory pattern to have control over all instantiations, but I'm not sure that IoC have such great design bug.
Is there a workaround for this situation or IoC really have such big defect in it's design? Maybe I should use another IoC container?
Any suggestions?
Seems to me that you are doing premature optimization: don't do it.
The constructors of your services should do nothing more than storing the dependencies that it takes in private fields. In that case the creation of such an object is really light weight. Don't forget that object creation in .NET is really fast. In most cases, from a performance perspective, it just doesn't matter whether those dependencies get injected or not. Especially when comparing to the amount of objects the rest of your application (and the frameworks you use) are spitting out. The real costs is when you start using web services, databases or the file system (or I/O in general), because they cause a much bigger delay.
If the creation is really expensive, you should normally hide the creation behind a Virtual Proxy instead of injecting a Lazy<T> in every consumer, since this allows common application code to stay oblivious to the fact that there is a mechanism to delay the creation (both your application code and test code are becoming more complex when you do this).
Chapter 8 of Dependency Injection: Principle, Practices, Patterns contains a more detailed discussion about lazy and Virtual Proxies.
However, a Lazy<T> just consumes 20 bytes of memory (and another 24 bytes for its wrapped Func<T>, assuming a 32bit process), and the creation of a Lazy<T> instance is practically free. So there is no need to worry about this, except when you’re in an environment with really tight memory constraints.
And if memory consumption is a problem, try registering services with a lifetime that is bigger than transient. You could do a per request, per web request, or singleton. I would even say that when you're in an environment where creating new objects is a problem, you should probably only use singleton services (but it's unlikely that you're working on such an environment, since you're building a web app).
Do note that Ninject is one of the slower DI libraries for .NET. If that's troubling you, switch to a faster container. Some containers have performance that is near newing up object graphs by hand.
but by all means, do profile this, many developers switch DI libraries for the wrong reasons.
Do note that the use of Lazy<T> as dependency is a leaky abstraction (a violation of the Dependency Inversion Principle). Please read this answer for more information.
Steven is correct in saying that this looks like premature optimization. The construction of these object is very fast and is usually never the bottleneck.
However using Lazy to express a dependency you don't need right away is a common pattern in Dependency Injection frameworks. Actofac is one such container that has built in support for various wrapping types. I'm sure there is also an extension for Ninject as well, maybe take a look at this one, Ninject Lazy.
You can also inject into an action method with the syntax below. (I'm not sure exactly what version this was introduced).
Constructor is best practice, but I had to do this once deliberately when I had a service that was doing some expensive initialization - accidentally in fact - but it wasn't discovered for a while and it was just easiest to move it to the one method that did need it.
This can make for cleaner code if you only need to access a service from one action method - but bear in mind if you inject it to the method you'll have to pass it around everywhere because it will no longer be on this. Definitely don't go assigning to this.service in an action method - that's horrible.
public IActionResult About([FromServices] IDateTime dateTime)
{
ViewData["Message"] = "Currently on the server the time is " + dateTime.Now;
return View();
}
https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/dependency-injection?view=aspnetcore-2.2#action-injection-with-fromservices
I am just starting to use Ninject on a (large) project and am wading in by only using DI for a portion of it to start. I have a subsystem that is organized using constructor injection extensively. Using Ninject to inject all of the dependencies between classes in this subystem is working great. However, I have dependencies on things outside of the subystem that I would really like to use Ninject to automatically inject as well, but not to be in charge of their lifecycle.
I thought Bind<T>.ToConstant(...) would work for what I am trying to do. For instance, I may have a class of type Monkey that is to act as a Singleton, but another part of my application is handling its lifecycle without Ninject (for example, creating it and disposing it manually). When my Ninject-equipped subsystem gets created I instantiate a kernel, bind my subsystem classes, and then use something like Bind<Monkey>.ToConstant(Monkey.Instance) to bind to various "external" dependencies. This works great at activation time but does not work as needed when I dispose the kernel. My subsystem can have a shorter lifecycle than these external dependencies, but when I call Dispose on the kernel all of these dependencies get disposed, which is not what I want. While I can see arguments both ways, it seems a bit questionable that Ninject would automatically dispose an object that it did not create. I'm hoping there is at least a way to opt out of this behavior, but so far I have not found anything. Is there any support for this?
Add InTransientScope to your constant object.
I'm a long-time Windows developer, having cut my teeth on win32 and early COM. I've been working with .NET since 2001, so I'm pretty fluent in C# and the CLR. I'd never heard of Castle Windsor until I started participating in Stack Overflow. I've read the Castle Windsor "Getting Started" guide, but it's not clicking.
Teach this old dog new tricks, and tell me why I should be integrating Castle Windsor into my enterprise apps.
Castle Windsor is an inversion of control tool. There are others like it.
It can give you objects with pre-built and pre-wired dependencies right in there. An entire object graph created via reflection and configuration rather than the "new" operator.
Start here: http://tech.groups.yahoo.com/group/altdotnet/message/10434
Imagine you have an email sending class. EmailSender. Imagine you have another class WorkflowStepper. Inside WorkflowStepper you need to use EmailSender.
You could always say new EmailSender().Send(emailMessage);
but that - the use of new - creates a TIGHT COUPLING that is hard to change. (this is a tiny contrived example after all)
So what if, instead of newing this bad boy up inside WorkflowStepper, you just passed it into the constructor?
So then whoever called it had to new up the EmailSender.
new WorkflowStepper(emailSender).Step()
Imagine you have hundreds of these little classes that only have one responsibility (google SRP).. and you use a few of them in WorkflowStepper:
new WorkflowStepper(emailSender, alertRegistry, databaseConnection).Step()
Imagine not worrying about the details of EmailSender when you are writing WorkflowStepper or AlertRegistry
You just worry about the concern you are working with.
Imagine this whole graph (tree) of objects and dependencies gets wired up at RUN TIME, so that when you do this:
WorkflowStepper stepper = Container.Get<WorkflowStepper>();
you get a real deal WorkflowStepper with all the dependencies automatically filled in where you need them.
There is no new
It just happens - because it knows what needs what.
And you can write fewer defects with better designed, DRY code in a testable and repeatable way.
Mark Seemann wrote and excellent book on DI (Dependency Injection) which is a subset of IOC. He also compares a number of containers. I cannot recommend this book enough. The book's name is: "Dependency Injection in .Net" https://www.manning.com/books/dependency-injection-in-dot-net
I think IoC is a stepping stone in the right direction on the path towards greater productivity and enjoyment of development team (including PM, BA an BOs). It helps to establish a separation of concerns between developers and for testing. It gives peace of mind when architecting which allows for flexibility as frameworks may come in and out.
The best way to accomplish the goal that IoC (CW or Ninject etc..) takes a stab at is to eliminate politics #1 and #2 remove need for developers to put on the facade of false understanding when developing. Do these two solutions not seem related to IoC? They are :)
Castle Windsor is Dependency Injection container. It means with the help of this you can inject your dependencies and use them without creating them with the help of new keyword.
e.g. Consider you have written a repository or a service and you wish to use it at many places, you need to first register your service / repository and you can start using it after injecting it on the required place.
You can take a look at the below tutorial which I followed to learn castle windsor.
link.
Hope it will help you.
Put simply. Imagine you have some class buried in your code that needs a few simple config values to do its job. That means everything that creates an instance of that class needs to get those dependencies, so you usually end up having to refactor loads of classes along the way to just pass a bit of config down to where the instance gets created.
So either lots of classes are needlessly altered, you bunch the config values into one big config class which is also bad... or worst still go Service Locator!
IoC allows your class to get all its depencencies without that hassle, and manages lifetimes of instances more explicitly too.