How to properly dispose objects: injected vs. owned - c#

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.

Related

How correctly to pass data from Singleton

I have Singleton class that get's data from web. And i need to pass those data to classes FirstDerived and SecondDerived. In this case is my class Singleton anti-pattern? Is it normal to use Aggregation relationship between DataSocket and FirstDerived, SecondDerived. Maybe it exist better object oriented solution?
namespace WpfApplication
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new TestViewModel();
}
}
public class TestViewModel
{
public ObservableCollection<Base> Items { get; set; }
public TestViewModel()
{
DataSocket.Instance.SendDataAsync();
Items = new ObservableCollection<Base>();
Items.Add(new FirstDerived(1, DataSocket.Instance));
Items.Add(new SecondDerived(2, DataSocket.Instance));
}
}
public abstract class Base
{
}
public class FirstDerived : Base, IDisposable
{
public FirstDerived(int id, DataSocket socket)
{
socket.Client += ProcessDataFromSocket;
}
public void ProcessDataFromSocket(string arg)
{
Console.WriteLine("First Derived getting data: {0}", arg.ToString());
}
public void Dispose()
{
throw new NotImplementedException();
}
}
public class SecondDerived : Base, IDisposable
{
public SecondDerived(int id, DataSocket socket)
{
DataSocket.Instance.Client += ProcessDataFromSocket;
}
public void ProcessDataFromSocket(string arg)
{
Console.WriteLine("Second Derived getting data: {0}", arg.ToString());
}
public void Dispose()
{
throw new NotImplementedException();
}
}
public sealed class DataSocket
{
private static DataSocket instance;
public delegate void Messages(string info);
public event Messages Client;
private DataSocket()
{
}
public void SendDataAsync()
{
Action Send = new Action(SendData);
IAsyncResult result = Send.BeginInvoke(null,null);
}
public void SendData()
{
while(true)
{
if (Client != null)
{
System.Threading.Thread.Sleep(3000);
Client("Test");
}
}
}
public static DataSocket Instance
{
get
{
if (instance==null)
{
instance = new DataSocket();
}
return instance;
}
}
}
}
To me it looks like DataSocket is the class that deals with networking, so any code to interact with the network should go there. Don't pass it into a constructor.
Rather, do something more like this sequence;
DataSocket.Instance.SendDataAsync();
Items = new ObservableCollection<Base>();
var data1 = await DataSocket.ReadData();
var data2 = await DataSocket.ReadData();
Items.Add(new FirstDerived(1, data1));
Items.Add(new SecondDerived(2, data2));
This way, your classes don't take a dependency on a global, constantly-changing object.
You might also want to consider some kind of lock statement to make sure that different parts of the code -- say, many different simultaneous web requests -- can't interfere with each other.

Passing dependency into Factory

We are using factory to create an instance of Subscribers. Each subscriber can have its own dependency.
Each subscriber will use constructor injection.
Should I pass dependency into subscribers through Subscriber Factory? Every time adding new dependency in any subscriber will change Subscriber factory?
public interface IMessageSubscriber
{
bool Process(string message)
}
public class MessageSubscriber1 : IMessageSubscriber
{
public bool Process(string message)
{
//Some custom logic
}
}
public class MessageSubscriber2 : IMessageSubscriber
{
public bool Process(string message)
{
//Some custom logic
}
}
public class MessageSubscriberFactory
{
//SubscriberType is enum
public IMessageSubscriber Get(SubscriberType type)
{
if(type == 1)
{
return new MessageSubscriber1();
}
else if(type == 2)
{
return new MessageSubscriber2();
}
}
}
//Main class
public class Process
{
public static void Main(string[] args)
{
MessageSubscriberFactory fac = new MessageSubscriberFactory();
foreach SubscriberType
{
string = "Message";
IMessageSubscriber subscriber = fac.Get(type);
subscriber.Process(message)
}
}
}
One approach would be to use named registrations with a DI/IOC container. This would involve using the container in a service locator fashion (which some people oppose), but I think it could make sense in this case. The example below is pretty crude, but it does give you an approach to handle subscribers with different dependencies without passing them into the factory. I used Unity here and you'd want to wrap the container reference rather than referencing directly, but this gets the point across.
public interface ILowerCaseWriter
{
void Write(string message);
}
public class LowerCaseWriter : ILowerCaseWriter
{
public void Write(string message)
{
Console.WriteLine(message.ToLower());
}
}
public interface IUpperCaseWriter
{
void Write(string message, int number);
}
public class UpperCaseWriter : IUpperCaseWriter
{
public void Write(string message, int number)
{
Console.WriteLine("{0}:{1}", number, message.ToUpper());
}
}
public interface ISubscriber
{
void Write();
}
public class Subscriber1 : ISubscriber
{
private ILowerCaseWriter _writer;
public Subscriber1(ILowerCaseWriter writer)
{
_writer = writer;
}
public void Write()
{
_writer.Write("Using subscriber 1");
}
}
public class Subscriber2 : ISubscriber
{
private IUpperCaseWriter _writer;
public Subscriber2(IUpperCaseWriter writer)
{
_writer = writer;
}
public void Write()
{
_writer.Write("Using subscriber 2", 2);
}
}
public class SubscriberFactory
{
private UnityContainer _container;
public SubscriberFactory()
{
_container = new UnityContainer();
_container.RegisterType<ILowerCaseWriter, LowerCaseWriter>();
_container.RegisterType<IUpperCaseWriter, UpperCaseWriter>();
_container.RegisterType<ISubscriber, Subscriber1>("Subscriber1");
_container.RegisterType<ISubscriber, Subscriber2>("Subscriber2");
}
public ISubscriber GetSubscriber(int type)
{
switch (type)
{
case 1:
return _container.Resolve<ISubscriber>("Subscriber1");
case 2:
return _container.Resolve<ISubscriber>("Subscriber2");
default:
throw new Exception();
}
}
}
class Program
{
private static void Main(string[] args)
{
var factory = new SubscriberFactory();
var subscriber = factory.GetSubscriber(1);
subscriber.Write();
Console.ReadLine();
}
}

WeakReference - Am I doing it right?

I have a static class, which exposes a event:
public static class MyStaticClass
{
static bool myBool= false;
public static bool MyBool
{
get { return myBool; }
private set
{
myBool= value;
var handler = MyBoolChanged;
if (handler != null)
handler(null, null);
}
}
public static event EventHandler MyBoolChanged;
}
And then I am registering to it using this pattern:
class AnotherClass
{
WeakReference _me;
public MyMethodInAnotherClass()
{
_me = new WeakReference(this);
MyStaticClass.MyBoolChanged+=
(_me.Target as AnotherClass).MyMethodInAnotherClassCallback;
}
private void MyMethodInAnotherClassCallback(some arguments)
{
}
}
What I want to achieve is that MyStaticClass will only execute the handler if the instance of AnotherClass has not been disposed (and has not deregistered).
The best way I can see to use this is to forget about an event, and use some kind of list instead; let's say List<WeakReference>; you could then have:
interface IFoo {
void Bar(some args);
}
with:
static class Whatever {
private static readonly List<WeakReference> items=new List<WeakReference>();
public static void Add(IFoo foo) {
if(foo != null) {
var newRef = new WeakReference(foo);
lock(items) { items.Add(newRef); }
}
}
public static void DoIt(some args) {
lock(items) {
foreach(var item in items) {
IFoo foo = item.IsAlive ? item.Target as IFoo : null;
if(foo != null) foo.Bar(some args);
}
}
}
}
with additional mechanisms to remove a specific IFoo, and to remove all dead foos left todo.
Then you just need AnotherClass : IFoo, with a Bar() implementation that applies your callback.
Additional emphasis: static collections (including events) are fairly dangerous; you must have some kind of sweep occasionally to remove empty items, and try to unsubscribe promptly where possible (in Dispose(), for example). As an illustration:
public static void Remove(IFoo foo) {
lock (items) { // also remove any dead debris
items.RemoveAll(x => !x.IsAlive || x.Target == foo || x.Target == null);
}
}

How to refactor these locks?

The naive solution, to move the lock to the Parent class, has a different behaviour: I will not be able to call new Child1().Method1() and new Child2().Method1() simultaneously.
Is there any way to refactor the code below?
abstract class Parent
{
protected abstract Method1();
}
class Child1 : Parent
{
static object staticLock = new object();
public void Method1()
{
lock(staticLock)
{
// Do something ...
}
}
}
class Child2 : Parent
{
static object staticLock = new object();
public void Method1()
{
lock(staticLock)
{
// Do something else ...
}
}
}
I'm asking this because it's not only 2 child classes, so the real problem is bigger.
Have a method implemented by each child class that provides lock policy and move Method1 to base class as in your other question.
class Parent
{
public void Method1()
{
using(acquireLock())
{
Method1Impl();
}
}
protected abstract IDisposable acquireLock();
protected abstract void Method1Impl();
}
class Child : Parent
{
protected override IDisposable acquireLock()
{
// return some class that does appropriate locking
// and in Dispose releases the lock.
// may even be no-op locking.
}
}
Maybe this works
abstract class Parent
{
protected abstract object StaticLock { get; }
public void Method()
{
lock(staticLock)
{
MethodImpl();
}
}
protected abstract MethodImpl();
}
class Child1 : Parent
{
private static object staticLock = new object();
protected override object StaticLock { get { return staticLock; } }
protected override MethodImpl()
{
// Do something ...
}
}
class Child2 : Parent
{
private static object staticLock = new object();
protected override object StaticLock { get { return staticLock; } }
protected override MethodImpl()
{
// Do something else ...
}
}

How to I write a repository with effective Dispose() in EF 3.5 -4.0?

i try to write a kind of repository for effective Add,Update, Delete etc. But i am so confused how can i dispose my 2 class ( ErpEntities and DataRepository) there are more advise but also more conflicts on google. i want to make disposing after return value. Shorthly and effectivelly :(
Best regards...
namespace WinApp.EF
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnSave_Click(object sender, EventArgs e)
{
using (ErpEntities erp = new ErpEntities())
{
erp.SaveCustomer(textBox1.Text, textBox2.Text);
}
}
}
public class ErpEntities : IDisposable
{
public int SaveCustomer(string Name, string SurName)
{
using (DataRepository<Customer> repository = new DataRepository<Customer>(new TestErpEntities()))
{
return repository.Add(new Customer() { Name = Name, SurName = SurName });
}
}
public void Dispose()
{
GC.SuppressFinalize(this);
}
}
public interface IRepository<T> : IDisposable where T : class
{
int Add(T entity);
}
public class DataRepository<T> : IRepository<T> where T : class
{
private TestErpEntities _context;
public DataRepository()
{
}
public DataRepository(TestErpEntities context)
{
_context = context;
}
public int Add(T entity)
{
_context.AddObject(typeof(T).Name, entity);
int saveValue = _context.SaveChanges();
return saveValue;
}
public void Dispose()
{
if (_context != null)
_context.Dispose();
}
}
}
I think this is what you want:
public class ErpEntities : IDisposable
{
public int SaveCustomer(string Name, string SurName)
{
using(DataRepository repository = new DataRepository<Customer>(new TestErpEntities()))
{
return repository.Add(new Customer() { Name = Name, SurName = SurName });
} // This using statment ensures that the DataRepository is Dispose()'d when the method exits
}
#region IDisposable Members
public void Dispose()
{
// You could eliminate this as there's nothing in your
// ErpEntities class that needs disposing
}
#endregion
}
public class DataRepository<T> : IRepository<T> where T : class
{
private TestErpEntities _context;
public DataRepository()
{
}
public DataRepository(TestErpEntities context)
{
_context = context;
}
public int Add(T entity)
{
_context.AddObject(typeof(T).Name, entity);
int saveValue = _context.SaveChanges();
return saveValue;
}
public void Dispose()
{
if (_context != null)
_context.Dispose();
}
}
The class destructor (~DataRepository()) and the GC.SupressFinalizer() are not necessary because you don't have any unmanaged resources to release. Many would argue that it's part of the IDisposable pattern, but IMO it's unnecessary.
Also, this:
new DataRepository<Customer>().Dispose();
is completely redundant and unnecessary. What you're doing here is creating this object only to destroy it. It has no other function and is just waste of memory/cpu cycles.
From what you posted, ErpEntities doesn't need to implement IDisposable. It doesn't 'own' anything.
If it did, new ErpEntities().SaveCustomer(...) would be the wrong way to use it.
The DataRepository class doesn't need the destructor (~DataRepository()) and the call(s) to GC.SuppressFinalize(this) can all be removed too.
What you should be left with:
if a class contains (owns) an IDisposable class it should implement IDisposable as well and forward the calls to Dispose()
the calling code should use IDisposable classes in a using(...) { } block.
don't mess with destructors unless you have an unmamaged resource (and even then there are better options)

Categories

Resources