Implementing the IDisposable interface - idisposable

public class MovieModel
{
public string id { get; set; }
public string title { get; set; }
public string image { get; set; }
public string cnt { get; set; }
}
public class DataSetHolder
{
public DataSet Data = new DataSet();
public Hashtable DataAdapters = new Hashtable();
public SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString);
}
Do I need to implement the IDisposable interface for both the classes?

You don't need to implement IDisposable for MovieModel. The garbage collector will take care of it. You might implement IDisposable for DataSetHolder. Please read the IDisposable documentation from MSDN to see how and when IDisposable should be used.
The primary use of this interface is to release unmanaged resources. The garbage collector automatically releases the memory allocated to a managed object when that object is no longer used. However, it is not possible to predict when garbage collection will occur. Furthermore, the garbage collector has no knowledge of unmanaged resources such as window handles, or open files and streams.

You implement IDispose:
a. Because you have UNmanaged resource (raw file handles etc) that you need to free - a very rare case. OR
b. Because you want to explicitly control access lifetime to resource controlled by managed objects.
Neither a. or b. apply to MovieModel. It does not contain any disposable objects that access resources you want control the lifetime off. No IDisposable implementation necessary.
For DataSetHolder a. does not apply, b. however may because it holds an SqlConnection object that manages a resource (the db connection). This is quite particular case because that resource is pooled. You could provide a mimimal IDisposable implementation and in your Dispose just dispose the connection (returning it to the connection pool). That would enable users of DataSetHolder to dispose it manually or to make use of a "using" block to control the lifetime of the connection.
public class DataSetHolder : IDisposable {
...
void Dispose() {
if (connection!=null)
connection.Dispose();
}
}
It may however (see here) be better just to ensure within DataSetHolder that when ever you use the connection you close it when done (i.e by wrapping all useage of the connection within DataSetHolder in a using statement). That way you are not holding the connection away from the pool unnecessarily. If the connection is freed in this manner on EVERY use then there is no need to implement IDispose (and app will scale better).
public class DataSetHolder {
...
void DoSomething() {
using (connection) {
...
}
}
void DoSomethingElse() {
using (connection) {
...
}
}
// No need for Dispose - the connection is disposed each time we use it.
}

Related

Connection String retrieved from one DB to be used in a Class Library to access a 2nd DB...Suggestions?

Environment:
.Net, SQL Server, WinForms Desktop
Control Database (db1)
Customer Databases (db2, db3, db4, etc.)
Background:
Each of our customers requires their own database. It's a contractual obligation due to compliance with standards in certain industries. Certain users of our application only have access to specific databases.
Scenario:
The application user's username gets passed into our control database (db1) from the app on load. There's a lookup in there that determines what customer this user has access to and returns connection string info for connecting to the database of the determined customer (db2 or db3 or db4 or etc.) to be used for the life of the runtime. All of my business logic is in a DAL, as it should be, in a .Net class library.
Suggestions on the best way/ways to get the connection string information into the DAL WITHOUT passing into every constructor/method that is called on the DAL.
I came up with one possible solution, but want to pick your brains to see if there's another or better way.
Possible Solutions:
A Global module in the DAL that has public fields like "dbServer" and "dbName".
Set those and then use the DAL as needed. They would need to be set each time the DAL is used throughout the application, but at least I don't have to make the signature of every single constructor and method require connection string information.
A settings file (preferably XML) that the app writes to after getting the connection info and the DAL reads from for the life of the runtime.
Thoughts and/or suggestions? Thanks in advance.
A set up like this might help. If you are going the IoC way, then you can remove the parameterized constructor and make Connection object a dependency too. However, you will need to feed your dependency injection provider in code since connection string comes from database.
public class User
{
public string ConnectionString
{
get; set;
}
}
public class SomeBusinessEntity
{
}
public class CallerClass
{
public IBaseDataAccess<SomeBusinessEntity> DataAccess
{
get;
set;
}
public void DoSomethingWithDatabase(User user)// Or any other way to access current user
{
// Either have specific data access initialized
SpecificDataAccess<SomeBusinessEntity> specificDataAccess = new SpecificDataAccess<SomeBusinessEntity>(user.ConnectionString);
// continue
// have dependency injection here as well. Your IoC configuration must ensure that it does not kick in until we get user object
DataAccess.SomeMethod();
}
}
public interface IBaseDataAccess<T>
{
IDbConnection Connection
{
get;
}
void SomeMethod();
// Other common stuff
}
public abstract class BaseDataAccess<T> : IBaseDataAccess<T>
{
private string _connectionString;
public BaseDataAccess(string connectionString)
{
_connectionString = connectionString;
}
public virtual IDbConnection Connection
{
get
{
return new SqlConnection(_connectionString);
}
}
public abstract void SomeMethod();
// Other common stuff
}
public class SpecificDataAccess<T> : BaseDataAccess<T>
{
public SpecificDataAccess(string connectionString) : base(connectionString)
{
}
public override void SomeMethod()
{
throw new NotImplementedException();
}
public void SomeSpecificMethod()
{
using (Connection)
{
// Do something here
}
}
}
Create a ConnectionStringProvider class that will provide you the connection string
public class ConnectionStringProvider
{
// store it statically so that every instance of connectionstringprovider
// uses the same value
private static string _customerConnectionString;
public string GetCustomerConnectionString()
{
return _customerConnectionString;
}
public void SetCustomerConnectionString(string connectionString)
{
_customerConnectionString = connectionString;
}
}
Using ConnectionStringProvider in your DAL
public class MyCustomerDAL
{
private ConnectionStringProvider _connectionStringProvider;
public MyCustomerDAL()
{
_connectionStringProvider = new ConnectionStringProvider();
}
public void UpdateSomeData(object data)
{
using (var con = new SqlConnection(
connectionString: _connectionStringProvider.GetCustomerConnectionString()))
{
//do something awesome with the connection and data
}
}
}
Setting/changing the connection string
new ConnectionStringProvider()
.SetCustomerConnectionString(connString);
Note
The reason i chose to use method instead of a get/set property in ConnectionStringProvider is because maybe in the future you decide to read/write these from a file, and while you could read/write from file in a property it's misleading to your consumer who thinks that a property will be a simple performance-less hit.
Using a function tells your consumer there might be some performance hit here, so use it wisely.
A little abstration for unit testing
Here is a slight variation that will enable you to abstract for unit testing (and eventually IoC)
public class MyCustomerDAL
{
private IConnectionStringProvider _connectionStringProvider;
public MyCustomerDAL()
{
//since not using IoC, here you have to explicitly new it up
_connectionStringProvider = new ConnectionStringProvider();
}
//i know you don't want constructor, i included this to demonstrate how you'd override for writing tests
public MyCustomerDAL(IConnectionStringProvider connectionStringProvider)
{
_connectionStringProvider = connectionStringProvider;
}
public void UpdateSomeData(object data)
{
using (var con = new SqlConnection(
connectionString: _connectionStringProvider.GetCustomerConnectionString()))
{
//do something awesome with the connection and data
}
}
}
// this interface lives either in a separate abstraction/contracts library
// or it could live inside of you DAL library
public interface IConnectionStringProvider
{
string GetCustomerConnectionString();
void SetCustomerConnectionString(string connectionString);
}
public class ConnectionStringProvider : IConnectionStringProvider
{
// store it statically so that every instance of connectionstringprovider uses the same value
private static string _customerConnectionString;
public string GetCustomerConnectionString()
{
return _customerConnectionString;
}
public void SetCustomerConnectionString(string connectionString)
{
_customerConnectionString = connectionString;
}
}
Appendix A - Using IoC and DI
Disclaimer: the goal of this next piece about IoC is not to say one way is right or wrong, it's merely to bring up the idea as another way to approach solving the problem.
For this particular situation Dependency Injection would make your solving the problem super simple; specifically if you were using an IoC container combined with constructor injection.
I don't mean it would make the code more simple, that would be more or less the same, it would make the mental side of "how do I easily get some service into every DAL class?" an easy answer; inject it.
I know you said you don't want to change the constructor. That's cool, you don't want to change it because it is a pain to change all the places of instantiation.
However, if everything were being created by IoC, you would not care about adding to constructors because you would never invoke them directly.
Then, you could add services like your new IConnectionStringProvider right to the constructor and be done with it.

Transition from Entityspaces(Tiraggo) into Servicestack Ormlite

at this moment we are migrating from Entityspaces(Tiraggo) into Servicestack Ormlite.
One point is the way to open and close the DBConnection.
I apologize for the comparission but it is useful for the question. In Tiraggo, inside my wep application, in the global.asax.cs I put this:
protected void Application_Start(object sender, EventArgs e)
{
Tiraggo.Interfaces.tgProviderFactory.Factory = new Tiraggo.Loader.tgDataProviderFactory();
}
In web.config exists the section for Tiraggo, the connectionstring and the ORM does the rest.
During the use of the classes we just do this:
User user = new User(); user.Name="some"; user.Comment = "some"; user.Save();
I dont open, close a DBConnection. It is transparent for the programmer. Just create the instance classes and use them.
I define a class, a repository and that's all. No DB definition or interaction. Everything happens in a webforms app, with the datalayer inside the same app.
When we are migrating to Servicestack ORMLite, I see the open of the DBConnection is too inside the globlal.asax.cs, but it references a Service no a class or repository.
public class AppHost : AppHostBase
{
public AppHost() : base("Hello ServiceStack", typeof(HelloService).Assembly) {}
public override void Configure(Container container) {}
}
So my first question is: how can I use it if I dont have a Service (HelloService), I have just classes or repositories. So I cant use this technique for DBConnection my DB.
I also see that accesing the Db, I need a open connection. I try to do this:
using (var Db = DbFactory.Conn.OpenDbConnection())
{
return Db.SingleById<Anio>(id);
}
Later, I found a sample like I was looking for, the Pluralsight video ".NET Micro ORMs" Steve Mihcelotti, and he just open the connection, but never Close it, never use the "using" syntax.
So my 2 questions are:
1) Is there a way for open the DbFactory(dbConnection) like all the samples using servicestack ormlite, but without using a Services ( I dont use Services, I want to use Ormlite but just with classes and repositories)
2) Is there a way for connnect to the database in each trip to the class or repository without using the "using" syntax, or
3) the only way is the one showed in the Pluralsight video, ie. open the connection throw the using syntax in each Method (trip to the class)
I hope I was clear.
The nice thing about IDbConnectionFactory is that it's a ThreadSafe Singleton which can be safely passed around and referenced as it doesn't hold any resources open itself (i.e. DB Connections).
A lazy pattern which provides a nice call-site API is the RepositoryBase class:
public abstract class RepositoryBase : IDisposable, IRepository
{
public virtual IDbConnectionFactory DbFactory { get; set; }
IDbConnection db;
public virtual IDbConnection Db
{
get { return db ?? (db = DbFactory.OpenDbConnection()); }
}
public virtual void Dispose()
{
if (db != null)
db.Dispose();
}
}
This is the same pattern ServiceStack's Service class uses to provide a nice API that only gets opened when it's used in Services, e.g:
public class MyRepository : RepositoryBase
{
public Foo GetFooById(int id)
{
return Db.SingleById<Foo>(id);
}
}
Note: This pattern does expect that your dependencies will be disposed after use.
Another alternative is to leverage your IOC to inject an Open IDbConnection with a managed lifetime scope, e.g:
container.Register<IDbConnection>(c =>
c.Resolve<IDbConnectionFactory>().OpenDbConnection())
.ReusedWithin(ReuseScope.Request);
The life-cycle of the connection is then up to your preferred IOC.
Without Using an IOC
Whilst it's typically good practice to use an IOC to manage your Apps dependencies and provide loose-coupling, if you don't want to use an IOC you can also make DbFactory a static property, e.g:
public abstract class RepositoryBase : IDisposable
{
public static IDbConnectionFactory DbFactory { get; set; }
IDbConnection db;
public virtual IDbConnection Db
{
get { return db ?? (db = DbFactory.OpenDbConnection()); }
}
public virtual void Dispose()
{
if (db != null)
db.Dispose();
}
}
Which you can just initialize directly on startup, e.g:
protected void Application_Start(object sender, EventArgs e)
{
RepositoryBase.DbFactory = new OrmLiteConnectionFactory(
connectionString, SqlServer.Provider);
}
Note: If you're not using an IOC then you want to make sure that instances of your repository classes (e.g. MyRepository) are disposed of after use.

Adapter Pattern: Class Adapter vs Object Adapter

I have a few questions about the Adapter pattern. I understand that the class adapter inherits from the adaptee while the object adapter has the adaptee as an object rather than inheriting from it.
When would you use a class adapter over an object adapter and vice versa? Also, what are the trade-offs of using the class adapter and the trade-offs of the object adapter?
I can see one advantage for the object adapter, depending on your programming language: if the latter does not support multiple inheritance (such as Java, for instance), and you want to adapt several adaptees in one shot, you'll be obliged to use an object adapter.
Another point for object adapter is that you can have the wrapped adaptee live his life as wanted (instantiation notably, as long as you instantiate your adapter AFTER your adaptee), without having to specify all parameters (the part for your adapter AND the part for your adaptee because of the inheritance) when you instantiate your adapter. This approach appears more flexible to me.
Prefer to use composition, over inheritance
First say we have a user;
public interface IUser
{
public String Name { get; }
public String Surname { get; }
}
public class User : IUser
{
public User(String name, String surname)
{
this.Name = name;
this.Surname = surname;
}
public String Name { get; private set; }
public String Surname { get; private set; }
}
Now, imagine that for any reason, youre required to have an adapter for the user class, we have then two aproaches, by inheritance, or by composite;
//Inheritance
public class UserAdapter1 : User
{
public String CompleteName { get { return base.Name + " " + base.Surname } }
}
//Composition
public class UserAdapter2
{
private IUser user;
public UserAdapter2(IUser user)
{
this.user = user;
}
public String CompleteName { get { return this.user.Name + " " + this.user.Surname; } }
}
You are totally ok, but just if the system don't grow... Imagine youre required to implement a SuperUser class, in order to deal with a new requirement;
public class SuperUser : IUser
{
public SuperUser(String name, String surname)
{
this.Name = name;
this.Surname = surname;
}
public String Name { get; private set; }
public String Surname { get; private set; }
public Int32 SupernessLevel { get { return this.Name.Length * 100; } }
}
By using inheritance you would not be able to re-use your adapter class, messing up your code (as your would have to implement another adapter, inheriting from SuperUser that would do ECXATLY the same thing of the other class!!!)... Interface usage is all about uncopling, thats the main reason that I'm 99% likely to use them, of course, if the choice is up to me.
Class Adapter is plain old Inheritance, available in every object-oriented language, while Object Adapter is a classic form of an Adapter Design Pattern.
The biggest benefit of Object Adapter compared to Class Adapter ( and thus Inheritance ) is loose coupling of client and adaptee.
A class adapter uses multiple inheritance to adapt one interface to another: (depending on your programming language: Java & C# does not support multiple inheritance)
An object adapter depends on object composition:
Images Source: Design Pattern (Elements of Reusable Object-Oriented Software) book
class adapters adapts Adaptee to Target by committing to a specific Adapter class will not work when we want to adapt a class and its subclasses.
object adapters lets a single Adapter work with many Adaptees (the Adaptee and all adaptees hierarchy)
In addition to what renatoargh has mentioned in his answer I would like to add an advantage of class adapter.
In class adapter you can easily override the behavior of the adaptee if you need to because you are just subclassing it. And it is harder in Object adapter.
However advantages of object adapter usually outweighs this tiny advantage of class adapter.

Force lazy entity to load real instance

I have a proxy for a lazy entity which has been created in the session by loading a child entity. A subsequent fetch on the parent entity only returns the NH proxy. I need the actual instance to check the type (the entity has joined subclasses). I must be missing something, but I can't find a way to do this. Session.Refresh(proxy) does not appear to help, nor does any flavour of HQL that I've tried.
Can anyone help?
In my opinion, rather then solving this problem, you should rather rethink your design. Are you absolutely sure, that you can't use polymorphism in this situation - either directly make entity responsible for operation you're trying to perform or use visitor pattern. I came across this issue few times and always decided to change design - it resulted in clearer code. I suggest you do the same, unless you're absolutely sure that relying on type is the best solution.
The problem
In order to have example with at least some resemblance to the real world, let's suppose you have following entities:
public abstract class Operation
{
public virtual DateTime PerformedOn { get; set; }
public virtual double Ammount { get; set; }
}
public class OutgoingTransfer : Operation
{
public virtual string TargetAccount { get; set; }
}
public class AtmWithdrawal : Operation
{
public virtual string AtmAddress { get; set; }
}
It'd naturally be a small part of much larger model. And now you're facing a problem: for each concrete type of Operation, there's a different way to display it:
private static void PrintOperation(Operation operation)
{
Console.WriteLine("{0} - {1}", operation.PerformedOn,
operation.Ammount);
}
private static void PrintOperation(OutgoingTransfer operation)
{
Console.WriteLine("{0}: {1}, target account: {2}",
operation.PerformedOn, operation.Ammount,
operation.TargetAccount);
}
private static void PrintOperation(AtmWithdrawal operation)
{
Console.WriteLine("{0}: {1}, atm's address: {2}",
operation.PerformedOn, operation.Ammount,
operation.AtmAddress);
}
Simple, overloaded methods will work in simple case:
var transfer = new OutgoingTransfer
{
Ammount = -1000,
PerformedOn = DateTime.Now.Date,
TargetAccount = "123123123"
};
var withdrawal = new AtmWithdrawal
{
Ammount = -1000,
PerformedOn = DateTime.Now.Date,
AtmAddress = "Some address"
};
// works as intended
PrintOperation(transfer);
PrintOperation(withdrawal);
Unfortunately, overloaded methods are bound at compile time, so as soon as you introduce an array/list/whatever of operations, only a generic (Operation operation) overload will be called.
Operation[] operations = { transfer, withdrawal };
foreach (var operation in operations)
{
PrintOperation(operation);
}
There are two solutions to this problem, and both have downsides. You can introduce an abstract/virtual method in Operation to print information to selected stream. But this will mix UI concerns into your model, so that's not acceptable for you (I'll show you how can you improve this solution to meet your expectations in a moment).
You can also create lots of ifs in form of:
if(operation is (ConcreteType))
PrintOperation((ConcreteType)operation);
This solution is ugly and error prone. Every time you add/change/remove type of operation, you have to go through every place you used these hack and modify it. And if you miss one place, you'll probably only be able to catch that runtime - no strict compile-time checks for some of errors (like missing one subtype).
Furthermore, this solution will fail as soon as you introduce any kind of proxy.
How proxy works
The code below is VERY simple proxy (in this implementation it's same as decorator pattern - but those patterns are not the same in general. It'd take some additional code to distinguish those two patterns).
public class OperationProxy : Operation
{
private readonly Operation m_innerOperation;
public OperationProxy(Operation innerOperation)
{
if (innerOperation == null)
throw new ArgumentNullException("innerOperation");
m_innerOperation = innerOperation;
}
public override double Ammount
{
get { return m_innerOperation.Ammount; }
set { m_innerOperation.Ammount = value; }
}
public override DateTime PerformedOn
{
get { return m_innerOperation.PerformedOn; }
set { m_innerOperation.PerformedOn = value; }
}
}
As you can see - there is only one proxy class for whole hierarchy. Why? Because you should write your code in a way that doesn't depend on concrete type - only on provided abstraction. This proxy could defer entity loading in time - maybe you won't use it at all? Maybe you'll use just 2 out of 1000 entities? Why load them all then?
So NHibernate uses proxy like on above (much more sophisticated, though) to defer entity loading. It could create 1 proxy per sub-type, but it would destroy whole purpose of lazy loading. If you look carefuly at how NHibernate stores subclasses you'll see, that in order to determine what type entity is, you have to load it. So it is impossible to have concrete proxies - you can only have the most abstract, OperationProxy.
Altough the solution with ifs it's ugly - it was a solution. Now, when you introduced proxies to your problem - it's no longer working. So that just leaves us with polymorphic method, which is unacceptable because of mixing UI responsibility to your model. Let's fix that.
Dependency inversion and visitor pattern
First, let's have a look at how the solution with virtual methods would look like (just added code):
public abstract class Operation
{
public abstract void PrintInformation();
}
public class OutgoingTransfer : Operation
{
public override void PrintInformation()
{
Console.WriteLine("{0}: {1}, target account: {2}",
PerformedOn, Ammount, TargetAccount);
}
}
public class AtmWithdrawal : Operation
{
public override void PrintInformation()
{
Console.WriteLine("{0}: {1}, atm's address: {2}",
PerformedOn, Ammount, AtmAddress);
}
}
public class OperationProxy : Operation
{
public override void PrintInformation()
{
m_innerOperation.PrintInformation();
}
}
And now, when you call:
Operation[] operations = { transfer, withdrawal, proxy };
foreach (var operation in operations)
{
operation.PrintInformation();
}
all works as a charm.
In order to remove this UI dependency in model, let's create an interface:
public interface IOperationVisitor
{
void Visit(AtmWithdrawal operation);
void Visit(OutgoingTransfer operation);
}
Let's modify model to depend on this interface:
And now create an implementation - ConsoleOutputOperationVisitor (I have deleted PrintInformation methods):
public abstract class Operation
{
public abstract void Accept(IOperationVisitor visitor);
}
public class OutgoingTransfer : Operation
{
public override void Accept(IOperationVisitor visitor)
{
visitor.Visit(this);
}
}
public class AtmWithdrawal : Operation
{
public override void Accept(IOperationVisitor visitor)
{
visitor.Visit(this);
}
}
public class OperationProxy : Operation
{
public override void Accept(IOperationVisitor visitor)
{
m_innerOperation.Accept(visitor);
}
}
What happens here? When you call Accept on operation and pass a visitor, implementation of accept will be called, where appropriate overload of Visit method will be invoked (compiler can determine type of "this"). So you combine "power" of virtual methods and overloads to get appropriate method called. As you can see - now UI reference here, model only depends on an interface, which can be included in model layer.
So now, to get this working, an implementation of the interface:
public class ConsoleOutputOperationVisitor : IOperationVisitor
{
#region IOperationVisitor Members
public void Visit(AtmWithdrawal operation)
{
Console.WriteLine("{0}: {1}, atm's address: {2}",
operation.PerformedOn, operation.Ammount,
operation.AtmAddress);
}
public void Visit(OutgoingTransfer operation)
{
Console.WriteLine("{0}: {1}, target account: {2}",
operation.PerformedOn, operation.Ammount,
operation.TargetAccount);
}
#endregion
}
And code:
Operation[] operations = { transfer, withdrawal, proxy };
foreach (var operation in operations)
{
operation.Accept(visitor);
}
I'm well aware that this isn't a perfect solution. You'll still have to modify the interface and visitors as you add new types. But you get compile time checking and will never miss anything. One thing that would be really hard to achieve using this method is to get pluggable subtypes - but I'm not convinced this is a valid scenario anyway. You'll also have to modify this pattern to meet your needs in concrete scenario, but I'll leave this to you.
To force a proxy to be fetched from the database, you can use the NHibernateUtil.Initialize(proxy) method, or access a method/property of the proxy.
var foo = session.Get<Foo>(id);
NHibernateUtil.Initialize(foo.Bar);
To check if an object is initialized or not, you can use the NHibernateUtil.IsInitialized(proxy) method.
Update:
To remove an object from the session cache, use the Session.Evict(obj) method.
session.Evict(myEntity);
Info about Evict and other methods for managing the session cache can be found in chapter 14.5 of the NHibernate docs.
Disabling lazy loading will force the actual instance to be returned instead of the NHibernate Proxy.
eg..
mapping.Not.LazyLoad();
or
<class name="OrderLine" table="OrderLine" lazy="false" >
Since the proxy is derived from the entity class, you can probably just check entity.GetType().BaseType to get your defined type.

IDisposable base class which owns managed disposable resource, what to do in subclasses?

I have a base class that owns a managed disposable resource (.NET PerformanceCounter). I understand about implementing IDisposable on the class so that I can explicitly call Dispose on the resource. From the examples I have seen, people typically use a private boolean member variable "disposed" and set it to true inside of Dispose. Later, if there is an attempt to access a public method or property, an ObjectDisposedException is raised if "disposed" is true.
What about in the subclasses? How would the subclasses, in their public methods and properties, know that that they had been disposed? At first I thought that the subclasses would not have to anything special (like implement their own version of Dispose) since the thing that needs to be disposed is only in the base class (let's assume that the subclasses won't be adding any data that needs to be explicitly disposed) and the base class' Dispose should handle that. Should the subclasses override the base class' virtual Dispose method solely for the purpose of setting its own "disposed" member variable?
Here is a very stripped-down version of the class hierarchy in question.
class BaseCounter : IBaseCounter, IDisposable
{
protected System.Diagnostics.PerformanceCounter pc;
private bool disposed;
public BaseCounter(string name)
{
disposed = false;
pc = CreatePerformanceCounter(name);
}
#region IBaseCounter
public string Name
{
get
{
if (disposed) throw new ObjectDisposedException("object has been disposed");
return pc.CounterName;
}
}
public string InstanceName
{
get
{
if (disposed) throw new ObjectDisposedException("object has been disposed");
return pc.InstanceName;
}
}
#endregion IBaseCounter
#region IDisposable
protected virtual void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing)
{
if (pc != null)
{
pc.Dispose();
}
pc = null;
disposed = true;
}
}
}
public void Dispose()
{
Dispose(true);
}
#endregion IDisposable
}
class ReadableCounter : BaseCounter, IReadableCounter //my own interface
{
public ReadableCounter(string name)
: base(name)
{
}
#region IReadableCounter
public Int64 CounterValue()
{
return pc.RawValue;
}
#endregion IReadableCounter
}
class WritableCounter : BaseCounter, IWritableCounter
{
public WritableCounter(string name)
: base(name)
{
}
#region IWritableCounter
public Increment()
{
pc.Increment();
}
#endregion IWritableCounter
}
In our system, ReadableCounter and WritableCounter are the only subclasses of BaseCounter and they are only subclassed to one more level via a code generation processes. The additional subclassing level only addes a specific name so that it becomes possible to create objects that correspond directly to named counters (e.g. if there is a counter that is used to count the number of widgets produced, it ends up being encapsulated in a WidgetCounter class. WidgetCounter contains the knowledge (really, just the counter name as a string) to allow the "WidgetCounter" performance counter to be created.
Only the code-generated classes are used directly by developers, so we would have something like this:
class WritableWidgetCounter : WritableCounter
{
public WritableWidgetCounter
: base ("WidgetCounter")
{
}
}
class ReadableWidgetCounter : ReadableCounter
{
public ReadableWidgetCounter
: base ("WidgetCounter")
{
}
}
So, you see that the base class owns and manages the PerformanceCounter object (which is disposable) while the subclasses use the PerformanceCounter.
If I have code like this:
IWritableCounter wc = new WritableWidgetCounter();
wc.Increment();
wc.Dispose();
wc.Increment();
wc = null;
How could WritableCounter know, in Increment, that it had been disposed? Should ReadableCoutner and WritableCounter simply override the BaseCounter's
protected virtual void Dispose(bool disposing)
something like this:
protected virtual void Dispose(bool disposing)
{
disposed = true; //Nothing to dispose, simply remember being disposed
base.Dispose(disposing); //delegate to base
}
simply to set a ReadableCounter/WritableCounter-level "disposed" member variable?
How about if the base class (BaseCounter) declared disposed as protected (or made it a protected property)? That way, the subclasses could refer to it rather than adding a Dispose method simply for the purpose of remembering that Dispose had happened.
Am I missing the boat on this?
I have seen some disposable classes with a public IsDisposed property. You could do that and check it in your sub-classes.
Another thing I've done is a generic protected 'Validate' method that all sub-class methods call (and could override). If it returns, all is well, otherwise it might throw. That would insulate your sub-classes from the disposable innards altogether.
I have snippets that I use for implementing IDisposable, both in the base class and in the subclasses. You'd probably want the one for the subclass.
I swiped most of this code from MSDN, I think.
Here's the code for the base class IDisposable (not the one you want):
#region IDisposable Members
// Track whether Dispose has been called.
private bool _disposed = false;
// Implement IDisposable.
// Do not make this method virtual.
// A derived class should not be able to override this method.
public void Dispose()
{
Dispose(true);
// Take yourself off the Finalization queue
// to prevent finalization code for this object
// from executing a second time.
GC.SuppressFinalize(this);
}
// Dispose(bool disposing) executes in two distinct scenarios.
// If disposing equals true, the method has been called directly
// or indirectly by a user's code. Managed and unmanaged resources
// can be disposed.
// If disposing equals false, the method has been called by the
// runtime from inside the finalizer and you should not reference
// other objects. Only unmanaged resources can be disposed.
protected virtual void Dispose(bool disposing)
{
// Check to see if Dispose has already been called.
if (!this._disposed)
{
// If disposing equals true, dispose all managed
// and unmanaged resources.
if (disposing)
{
// TODO: Dispose managed resources.
}
// Release unmanaged resources. If disposing is false,
// only the following code is executed.
// TODO: Release unmanaged resources
// Note that this is not thread safe.
// Another thread could start disposing the object
// after the managed resources are disposed,
// but before the disposed flag is set to true.
// If thread safety is necessary, it must be
// implemented by the client.
}
_disposed = true;
}
// Use C# destructor syntax for finalization code.
// This destructor will run only if the Dispose method
// does not get called.
// It gives your base class the opportunity to finalize.
// Do not provide destructors in types derived from this class.
~Program()
{
// Do not re-create Dispose clean-up code here.
// Calling Dispose(false) is optimal in terms of
// readability and maintainability.
Dispose(false);
}
#endregion
And here's the code I use in the subclasses (this is the code you want):
#region IDisposable Members
// Track whether Dispose has been called.
private bool _disposed = false;
// Design pattern for a derived class.
// Note that this derived class inherently implements the
// IDisposable interface because it is implemented in the base class.
// This derived class does not have a Finalize method
// or a Dispose method without parameters because it inherits
// them from the base class.
protected override void Dispose(bool disposing)
{
if (!this.disposed)
{
try
{
if (disposing)
{
// Release the managed resources you added in
// this derived class here.
// TODO: Dispose managed resources.
}
// Release the native unmanaged resources you added
// in this derived class here.
// TODO: Release unmanaged resources.
_disposed = true;
}
finally
{
// Call Dispose on your base class.
base.Dispose(disposing);
}
}
}
#endregion
Look for the TODO: marks.