Ninject Transient Scope with Dispose - c#

I have a console app that uses kernel.Get<SomeClass>(); However, SomeClass has a dependency on SomeDisposableClass. How can I set up my binding to dispose of SomeDisposableClass when SomeClass is garbage collected? My MVC app uses InRequestScope and that works great, but there doesn't seem to be an analogous scope for console apps.
Example here:
public class SomeClass {
public SomeClass(SomeDisposableClass c) {
this.C = c;
}
private SomeDisposableClass C { get; set; }
// ... Business Methods ... //
}
My module
kernel.Bind<ISomeClass>().To<SomeClass>().In???Scope()
My console app
public static void Main() {
SomeFunc();
SomeFunc();
Console.ReadLine();
}
public static void SomeFunc() {
ISomeClass someClass = kernel.Get<ISomeClass>();
// work
}
I'd like for SomeDisposableClass to be disposed when SomeFunc is finished (or when the garbage collector is called). But I'm not sure of which binding scope to use. InTransientScope doesn't ever call dispose. Do I just have to make SomeClass disposable and implement Dispose() and wrap all my usages in the console app with a using statement?

In Ninject2, you can do this by:
Bind<IService>().To<ServiceImpl>().InScope(ctx => ...);
For example, the callback used for InRequestScope() is:
ctx => HttpContext.Current
Since HttpContext.Current is set to a new instance of HttpContext on each web request, only a single instance of the service will be activated for each request, and when the request ends and the HttpContext is (eventually) collected, the instances will be deactivated.
You can have a static variable within your console to reference an object that will control lifetime.
public static object LifetimeController = new object();
You can register this as your lifetime control object
Bind<IService>().To<ServiceImpl>().InScope(ctx => LifetimeController);
And each time you want to refresh the objects you can have a method like this
public static void StartNewLifetime()
{
LifetimeController = new object();
}
See here and here for more information

Use InTransientScope -- then the Ninject container will not hold any reference to the object. That way SomeClass will be GC'd when it goes out of scope at the end of SomeFunc. All you need to do is have its finalizer dispose of the SomeDisposableClass instance:
public class SomeClass : IDisposable {
~SomeClass() {
if (this.C != null) this.C.Dispose();
}
}
Here's how I was testing:
class Program
{
private static IKernel _kernel;
static void Main(string[] args)
{
_kernel = new StandardKernel();
_kernel.Bind<ISomeClass>().To<SomeClass>().InTransientScope();
while (true)
{
LifetimeController = new object();
SomeFunc();
Thread.Sleep(10);
}
}
public static void SomeFunc()
{
_kernel.Get<ISomeClass>();
}
public interface ISomeClass { }
public class SomeClass : ISomeClass
{
public SomeDisposableClass C = new SomeDisposableClass();
~SomeClass()
{
Console.WriteLine("{0} finalized", this);
C.Dispose();
}
}
public class SomeDisposableClass : IDisposable
{
private byte[] bytes = new byte[1000000];
public void Dispose()
{
Console.WriteLine("{0} disposed", this);
}
}
}

Related

What's the best way to call dispose on Unity Containers?

I have a a completed (and broken) C# app below that generates a stack overflow exception. If you review the source code, you'll see why there's a stack overflow exception, so I'm not really looking at diagnosing WHY it happens, I want to know what the best way of handling it is.
1) All references to unity are encapsulated inside a Class named Registry so I can upgrade without difficulty. I don't want unitycontainer littering other classes where possible. In theory, I should be able to upgrade to 5 if/when it comes out, or even swap it out with ninject or other DI framework if I were to have a drastic change of disposition.
2) I want the Registry to be controlled by the unity container so that it can be used in the constructors for the container controlled classes. (eg FirstSingleInstance)
3) Both IRegistry and Registry inherit from IDisposable because I assume it's good practice to dispose the unity containers.
4) Registry constructs the Unity Container in it's own constructor, so I assume I should also dispose the unity container when registry.dispose is called.
5) all other classes that are controlled by Registry are expected to be single instance classes, so I register them with a ContainerControlledLifetimeManager. I expect those instances will be disposed when the container gets disposed.
What is the best practice for dealing with this situation?
a) do not call dispose on Registry -- let it live for the life of the process thread?
b) Don't try to have Registry (and by extension, UnityContainer) controlled by the unity container. That way calling dispose on Registry won't cause a stackoverflow exception. How I would then have unity construct the FirstSingleInstance class is something I'd have to review.
d) other?
Here's the app that I wrote that has all the relevant pieces
using System;
using Microsoft.Practices.Unity;
namespace DIProblem.Console
{
class Program
{
static void Main(string[] args)
{
IRegistry registry = CreateRegistry();
IFirstSingleInstance theInstance = registry.Resolve<IFirstSingleInstance>();
theInstance.DoThis();
registry.Dispose(); // stack overflow here because of infinite dispose loop
}
static IRegistry CreateRegistry() => new Registry();
}
public class FirstSingleInstance : IFirstSingleInstance
{
private IRegistry _registry;
public FirstSingleInstance(IRegistry reg)
{
_registry = reg;
}
public void DoThis()
{
System.Console.WriteLine("This Was Done.");
_registry.Resolve<ISecondSingleInstance>().DoThisToo();
}
}
public class SecondSingleInstance : ISecondSingleInstance
{
private IRegistry _registry;
public SecondSingleInstance(IRegistry reg)
{
_registry = reg;
}
public void DoThisToo()
{
System.Console.WriteLine("This Was Done too.");
}
}
public interface ISecondSingleInstance
{
void DoThisToo();
}
public interface IFirstSingleInstance
{
void DoThis();
}
public class Registry : IRegistry, IDisposable
{
public Registry()
{
_container = new UnityContainer();
RegisterInstance<IFirstSingleInstance, FirstSingleInstance>();
RegisterInstance<ISecondSingleInstance, SecondSingleInstance>();
_container.RegisterInstance<IRegistry>(this);
}
private UnityContainer _container;
public void RegisterInstance<T1, T2>() where T2 : class, T1 => _container.RegisterType<T1, T2>(new ContainerControlledLifetimeManager());
public T Resolve<T>() => _container.Resolve<T>();
public void Dispose()
{
Dispose(true);
System.GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
_container?.Dispose();
_container = null;
}
}
public interface IRegistry : IDisposable
{
T Resolve<T>();
void RegisterInstance<T1, T2>() where T2 : class, T1;
}
}
Thank you for helping out in whatever way seems reasonable.
The following code refrains from using the Service Locator anti-pattern and instead relies solely on Constructor Injection as pattern for applying Inversion of Control. The result is a simpler, more maintainable and more testable application that doesn't cause any stackoverflow exceptions.
class Program
{
static void Main(string[] args)
{
using (var container = Registry.BuildContainer())
{
var theInstance = registry.Resolve<IFirstSingleInstance>();
theInstance.DoThis();
}
}
}
public static class Registry
{
public static UnityContainer BuildContainer()
{
var container = new UnityContainer();
container.RegisterType<IFirstSingleInstance, FirstSingleInstance>(Singleton);
container.RegisterType<ISecondSingleInstance, SecondSingleInstance>(Singleton);
return container;
}
private static ContainerControlledLifetimeManager Singleton =>
new ContainerControlledLifetimeManager();
}
public interface ISecondSingleInstance
{
void DoThisToo();
}
public interface IFirstSingleInstance
{
void DoThis();
}
public class FirstSingleInstance : IFirstSingleInstance
{
private ISecondSingleInstance _second;
public FirstSingleInstance(ISecondSingleInstance second)
{
_second = second;
}
public void DoThis()
{
System.Console.WriteLine("This Was Done.");
_second.DoThisToo();
}
}
public class SecondSingleInstance : ISecondSingleInstance
{
public SecondSingleInstance(/* other dependencies here */)
{
}
public void DoThisToo()
{
System.Console.WriteLine("This Was Done too.");
}
}

How to properly dispose objects: injected vs. owned

I have a question about disposing objects.
Consider this IDisposable class
public class MyClass : DisposableParentClass
{
private MyProp _prop;
public MyClass(MyProp prop)
{
_prop = prop;
}
public MyClass()
{
_prop = new MyProp();
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
_prop.Dispose();
}
base.Dispose(disposing);
}
}
On the first constructor, MyProp is injected. So MyClass is not the owner of the object. But on the second constructor, MyProp is created locally.
Should I always dispose MyProp, or should I check first if it is injected or not.
public class MyClass : DisposableParentClass
{
private MyProp _prop;
private bool _myPropInjected = false;
public MyClass(MyProp prop)
{
_prop = prop;
_myPropInjected = true;
}
public MyClass()
{
_prop = new MyProp();
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (!_myPropInjected) { _prop.Dispose(); }
}
base.Dispose(disposing);
}
}
If your class should handle these two situations:
It is not the owner of the provided object, it should not dispose of it
It is the owner of the created object, it should dispose of it
Then yes, you need to have a mechanism that tells these two situations apart.
A common method (common to me anyway) is to use naming convention like this:
private MyProp _prop;
private bool _ownsProp = false;
ie. reverse the meaning of your flags, but this is details, your solution is just fine, and yes, you need to have a solution like this.
If you have a ton of these fields, where each must have its own bool field to handle this, it might be worth creating a helper class, such as this LINQPad program demonstrates:
void Main()
{
Injectable i1 = new Injectable();
Injectable i2 = new Injectable(new Injected("A"));
Injectable i3 = new Injectable(new Injected("A"), new Injected("B"));
Debug.WriteLine("dispose a and b");
i1.Dispose();
Debug.WriteLine("dispose b");
i2.Dispose();
Debug.WriteLine("no dispose");
i3.Dispose();
}
public class Injected : IDisposable
{
public Injected(string name) { Name = name; }
public string Name { get; set; }
public void Dispose() { Debug.WriteLine(Name + " disposed"); }
}
public class Injectable : IDisposable
{
private Ownable<Injected> _A;
private Ownable<Injected> _B;
public Injectable(Injected a, Injected b)
{
_A = Ownable.NotOwned(a);
_B = Ownable.NotOwned(b);
}
public Injectable(Injected a)
{
_A = Ownable.NotOwned(a);
_B = Ownable.Owned(new Injected("B"));
}
public Injectable()
{
_A = Ownable.Owned(new Injected("A"));
_B = Ownable.Owned(new Injected("B"));
}
public void Dispose()
{
_A.Dispose();
_B.Dispose();
}
}
public class Ownable<T> : IDisposable
where T : class
{
private readonly T _Instance;
private readonly Action _CleanupAction;
public Ownable(T instance, bool isOwned)
{
_Instance = instance;
if (isOwned)
{
IDisposable disposable = instance as IDisposable;
if (disposable == null)
throw new NotSupportedException("Unable to clean up owned object, does not implement IDisposable");
_CleanupAction = () => disposable.Dispose();
}
}
public Ownable(T instance, Action cleanupAction)
{
_Instance = instance;
_CleanupAction = cleanupAction;
}
public T Instance { get { return _Instance; } }
public void Dispose()
{
if (_CleanupAction != null)
_CleanupAction();
}
}
public static class Ownable
{
public static Ownable<T> Owned<T>(T instance)
where T : class
{
return new Ownable<T>(instance, true);
}
public static Ownable<T> Owned<T>(T instance, Action cleanupAction)
where T : class
{
return new Ownable<T>(instance, cleanupAction);
}
public static Ownable<T> NotOwned<T>(T instance)
where T : class
{
return new Ownable<T>(instance, false);
}
}
A different note can be made here either.
It depends on what is your MyClass is doing actually.
For example, if we are talking about a class that reads video stream from device, after applies some filters to it and writes data to a user specified file, where file writing is made by stream passed from the outside, say like this:
public class VideoProcessor : IDisposable {
private FileStream _videoFile = null;
private VideoProcessor() {}
//user specified FileStream
public VideoProcessor(FileStream fs) {_videoFile = fs;}
public void Dispose() {
_videoFile.Dispose(); //Dispose user passed FileStream
}
}
disposing passed stream object during dispose call, makes actually sence.
In other cases, yes, it's better to not destroy object, if you are not an owner of it. Leave it to the caller to decide when it is appropriate time to do that.

New value from ThreadLocal<IDisposable> after .Value.Dispose()

Is there a built-in ThreadLocal<T>-like construct for sharing an object within each unique thread but recreating it if the original value was disposed/destructed/teared down/nulled?
Here's my attempt at implementing such behaviour with ConcurrentDictionary (the ThreadLocalDisposable2 below), but I was hoping to just use ThreadLocal<T> (as in ThreadLocalDisposable1), however I can't get the Foo test to pass, .Values.Remove(this) doesn't do what I was hoping it would do and still causes ObjectDisposedException.
public class Class1
{
[Test]
public void Foo()
{
using (var foo = ThreadLocalDisposable1.Get())
foo.Foo();
using (var foo = ThreadLocalDisposable1.Get())
foo.Foo();
}
[Test]
public void Bar()
{
using (var bar = ThreadLocalDisposable2.Get())
bar.Foo();
using (var bar = ThreadLocalDisposable2.Get())
bar.Foo();
}
}
[1]
public class ThreadLocalDisposable1 : IDisposable
{
private Stream _foo;
private static ThreadLocal<ThreadLocalDisposable1> _thread;
static ThreadLocalDisposable1()
{
_thread = new ThreadLocal<ThreadLocalDisposable1>(() => new ThreadLocalDisposable1(), true);
}
private ThreadLocalDisposable1()
{
_foo = new MemoryStream();
}
public static ThreadLocalDisposable1 Get()
{
return _thread.Value;
}
public void Foo()
{
_foo.WriteByte(1);
}
public void Dispose()
{
//I do not think it means what I think it means
_thread.Values.Remove(this);
_foo.Dispose();
}
}
[2]
public class ThreadLocalDisposable2 : IDisposable
{
private Stream _foo;
private int _thread;
private static ConcurrentDictionary<int, ThreadLocalDisposable2> _threads;
static ThreadLocalDisposable2()
{
_threads = new ConcurrentDictionary<int, ThreadLocalDisposable2>();
}
private ThreadLocalDisposable2(int thread)
{
_thread = thread;
_foo = new MemoryStream();
}
public static ThreadLocalDisposable2 Get()
{
return _threads.GetOrAdd(Thread.CurrentThread.ManagedThreadId, i => new ThreadLocalDisposable2(i));
}
public void Foo()
{
_foo.WriteByte(1);
}
public void Dispose()
{
ThreadLocalDisposable2 thread;
_threads.TryRemove(_thread, out thread);
_foo.Dispose();
}
}
Edit:
Just to clarify what I mean, basically I want all of the behaviour of ThreadLocal but when I call Dispose (on the value, the ThreadLocalDisposable* with underlying Stream in this example, not the static ThreadLocal itself) take that disposed instance out of circulation, i.e. if called upon again -- create a new value as if it's a brand new thread requiring a brand new instance.
The ThreadLocalDisposable1, [1], is sample class of what I think should've worked, except the .Values.Remove(this) line doesn't "take it out of circulation" and forces a new instance to be created for that thread.
The ThreadLocalDisposable2, [2], with ConcurrentDictionary, is a way I implemented alternative to ThreadLocal with "take out of circulation" behaviour I'm after.
Edit:
This is not the a real use case I have, just a general example I can think of, but if you have for example a static ThreadLocal<SqlConnection>, or a socket, and it's forcefully closed (and disposed in final block) -- drop that connection instance and create a new one transparently if called again.
It seems like you're making this much harder than it has to be. Consider this:
public class MyClass: IDisposable
{
private Stream _foo;
public MyClass Get()
{
if (_foo == null)
{
_foo = new MemoryStream();
}
}
public void Foo()
{
_foo.WriteByte(1);
}
public void Dispose()
{
if (_foo != null)
{
_foo.Dispose();
_foo = null;
}
}
}
Now, you can create one of those:
ThreadLocal<MyClass> MyThing = new ThreadLocal<MyClass>();
And you can write:
using (MyThing.Value.Get())
{
// do stuff
}
That seems functionally equivalent to what you're trying to do with your ConcurrentDictionary stuff.
That said, it seems like this is something that would be better managed another way. I don't know your application so I can't say for sure, but it seems like a bad idea to have a stateful object like a Stream or SqlConnection as a global variable. Usually those things are job-specific rather than thread-specific, and as such should be passed as parameters when you start the job.

Thread safety of C# singleton instance in ApplicationState

I have a bit of code that I've been trying to examine for thread safety. I'm using the basic lazy singleton model found here. I was wondering if it is still thread safe if I'm putting the instance in the HttpApplicationState object. I need to access this instance across all instances of the web application, so if this is not thread safe how can I make it thread safe?
public sealed class EmailWorker {
private HttpApplicationState _app;
private const EMAIL_WORKER = "EmailWorker";
EmailWorker() { }
class NestedWorker {
static NestedWorker() { }
internal static readonly EmailWorker Instance = new EmailWorker();
}
public static void Initialize(HttpApplicationState appState) {
_appState = appState;
_appState.Lock();
if (_appState[EMAIL_WORKER] == null) {
_appState.Add(EMAIL_WORKER, NestedWorker.Instance);
}
_appState.UnLock();
}
public static EmailWorker Instance {
get {
// TODO: If we haven't called Initialize() first then throw exception
return (EmailWorker)_appState[EMAIL_WORKER];
}
}
}
You don't need to use Application state at all.
It should be thread-safe, but why bother?
A "standard" singleton will also be accessible across the entire application, and it won't require injecting and keeping a reference to the HttpApplicationState:
public sealed class EmailWorker
{
private EmailWorker() { }
private static class NestedWorker
{
static NestedWorker() { }
internal static readonly EmailWorker Instance = new EmailWorker();
}
public static EmailWorker Instance
{
get { return NestedWorker.Instance; }
}
}

Is Structuremap singleton thread safe?

Currently I have the following class:
public class PluginManager
{
private static bool s_initialized;
private static object s_lock = new object();
public static void Initialize() {
if (!s_initialized) {
lock (s_lock) {
if (!s_initialized) {
// initialize
s_initialized = true;
}
}
}
}
}
The important thing here is that Initialize() should only be executed once whilst the application is running. I thought that I would refactor this into a singleton class since this would be more thread safe?:
public sealed class PluginService
{
static PluginService() { }
private static PluginService _instance = new PluginService();
public static PluginService Instance { get { return _instance; } }
private bool s_initialized;
public void Initialize() {
if (!s_initialized)
{
// initialize
s_initialized = true;
}
}
}
Question one, is it still necessary to have the lock here (I have removed it) since we will only ever be working on the same instance?
Finally, I want to use DI and structure map to initialize my servcices so I have refactored as below:
public interface IPluginService {
void Initialize();
}
public class NewPluginService : IPluginService
{
private bool s_initialized;
public void Initialize() {
if (!s_initialized) {
// initialize
s_initialized = true;
}
}
}
And in my registry:
ForRequestedType<IPluginService>()
.TheDefaultIsConcreteType<NewPluginService>().AsSingletons();
This works as expected (singleton returning true in the following code):
var instance1 = ObjectFactory.GetInstance<IPluginService>();
var instance2 = ObjectFactory.GetInstance<IPluginService>();
bool singleton = (instance1 == instance2);
So my next question, is the structure map solution as thread safe as the singleton class (second example). The only downside is that this would still allow NewPluginService to be instantiated directly (if not using structure map).
Many thanks,
Ben
I would make several recommendations:
the boolean flag should be volatile
make your singleton instance readonly
the initialization is not thread safe, regardless of the fact that you have only one instance... so it should be synchronized
public sealded class PluginService
{
static PluginService() { }
//make the instance readonly
private static readonly PluginService _instance = new PluginService();
public static PluginService Instance { get { return _instance; } }
// make the flag volatile
private static volatile bool s_initialized = false;
private static object s_lock = new object();
// you still need to synchronize when you're initializing
public void Initialize() {
lock(s_lock)
{
if (!s_initialized)
{
// initialize
s_initialized = true;
}
}
}
}
There is no contention on the structured map, so its thread safety doesn't seem compromised...
The singleton class you had was not thread safe. The main thing to remember is that a single instance does not ensure a single thread can only access it. If there are multiple threads that have a reference to the instance, then there is contention on the instance and the data it's holding. If there is contention then you should ensure thread safety (synchronize at the very minimum).

Categories

Resources