1

I have a disposable class which implements IDisposalbe interface with disposable pattern. To maintain the constrains, I need to make sure that when the object has been disposed, any subsequent call to any public method throws ObjectDisposedException. The obvious solution is to check a bool value isDisposed and throw an exception. But how can I use some reflection based solution (if any or some other approach) to automatically apply this constrain to every public method. What I don’t want to do is to do this check in every method I have (i.e. prior to every call I do NOT want to call IsObjectDisposed() method)

Apart from the practical application as I have described earlier I need to know a way to automatically call a method let’s say Foo() for every call of a method of a class say MyClass

meshy
  • 8,470
  • 9
  • 51
  • 73
Sriwantha Attanayake
  • 7,694
  • 5
  • 42
  • 44

2 Answers2

2

Imo, you have 2 solutions here:

  • or call them manually, so code actually, that for every public method the check is executed.

  • or can use Aspect Oriented Programming to inject the function call into the begining of every method marked by some attribute.

Tigran
  • 61,654
  • 8
  • 86
  • 123
  • 1
    So how to do this. I guess I have to add create an attribute? – Sriwantha Attanayake Oct 04 '12 at 09:32
  • @Sriwantha: first read article see how it *works* in general. You can do **a lot of** cool, things with *aspects*. The other side of coin of it is that the code is generated on successful compilation, so the *binary* is different from the code you *actually* have in editor. – Tigran Oct 04 '12 at 09:37
  • I agree what you have said. I have used aspects for several cache implementations and thread prioritization. But this is a special case where I need to apply this feature fore every method without decorating every method with an attribute. Is there a way to define an aspect at one place (may be as a class attribute) where I can define this constrain so that anybody who is adding a new method don't want to worry about applying that attribute (aspect) – Sriwantha Attanayake Oct 04 '12 at 09:46
  • @Sriwantha: look on examples, there is plenty of them, for example automatic logging. Which is basically injected log method call in every method. It *should* be possible (but not very sure) to achieve that *without* attributes too. – Tigran Oct 04 '12 at 09:51
0

Have you thought about simply performing a null check prior to using the code?

ie. if(null!=object) { do operations }

Or are you looking for some kind of object wrapper instead using the virtual keyword? ie use Aspects using unity for example or spring. These allow you to Dependency Inject code into your application and allow you to apply "cross cutting concerns" through your code base ie security, logging, printing and boundary checking.

CodeCaster
  • 147,647
  • 23
  • 218
  • 272