Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

StructureMap remove a single instance

Does anyone know how to remove a single instance from the object cache? I have a class for which I get instances using StructureMap. At some time, an instance can get invalid, so I want to remove it from the cache, to make sure that the next time I call ObjectFactory.GetInstance, I get a newly created instance. This should work with different kinds of lifecycles.

I don't want to remove all instances of that type, nor any other instances for other types.

like image 947
rekna Avatar asked Mar 14 '26 12:03

rekna


1 Answers

When you need to replace an instance of a registered service with a new one because of corruption, this typically indicates that instance lives too long. A DataContext is a good example. A DataContext should not outlive the (web) request it is created in, since it is not thread-safe. Even when you're not dealing with a web application, there is typically some sort of request in which you operate and each request gets its own DataContext instance.

In case an exception occurs, you should typically abort the complete operation as fast as you can. Trying to recover and continue is in general considered to be a bad thing in most cases. This is a general software principle, and has nothing to do with DI. In most cases you don't know exactly what went wrong and continuing could even make things worse. Continuing will not make your application more robust. It will just make it much harder to find bugs.

Long story short: you should cache a DataContext at most for the lifetime of a single request and don't try to replace it when an exception occurs. Just let the request fail (and log all information you need to find the bug and fix it).

If you're running an ASP.NET application, you can configure the DataContext instance as HttpContextScoped.

like image 50
Steven Avatar answered Mar 16 '26 00:03

Steven



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!