13

If I am executing within the context of a particular service instance and operation, how do I get access to the currently-executing service instance? Service instances don't inherit from any specific common base class or interface and the only pathway into the existing context that I can find is:

OperationContext.Current

but I can't seem to find any properties that reference the actual service instance itself so that I can cast it to what I know it should be and perform operations on it.

Without exploring why I am doing this (it's irrelevant), please let me know if there is any way to find the reference I am looking for.

EDIT:

[ServiceContract]
public interface IInventory
{
    [OperationContract]
    List<DealInfo> ListDeals(DealQueryOptions options);
}

// This is the object I will need access to the current instance of
public class Inventory : ServiceBase<Inventory>, IInventory
{
    public List<DealInfo> ListDeals(DealQueryOptions options)
    {
        var obj = new Whatever(); // see below
    }
}

public class Whatever
{
    public Whatever()
    {
        // how do I get access to the service instance here?
        // assume that in this context we are not allowed to
        // pass the service instance to this class; this class
        // must automatically discover the instance itself.
    }
}
abatishchev
  • 98,240
  • 88
  • 296
  • 433
Nathan Ridley
  • 33,766
  • 35
  • 123
  • 197
  • Sorry, could you explain a little more exactly what you are looking for? OperationContext.Current should provide everything you need in one way or another. – Christian Hayter Jun 30 '09 at 08:47
  • I've updated the question with an example. – Nathan Ridley Jun 30 '09 at 09:15
  • It looks like you don't control the source code of the "Whatever" class, but you still want to pass instance data into it. Am I right? – Christian Hayter Jun 30 '09 at 09:34
  • Actually `Whatever` is part of our repository library which does some nifty autosubscription stuff. The style of implementation requires the implementation to discover things on its own, sort of like the methodology behind the usage of TransactionScope. – Nathan Ridley Jun 30 '09 at 09:38
  • I feel your pain. Our custom EntLib exception handlers and trace listeners have to discover a lot of things via static properties. I've never had to discover the actual service class though. :-) – Christian Hayter Jun 30 '09 at 09:47

2 Answers2

18
var myService = OperationContext.Current.InstanceContext.GetServiceInstance();
Nathan Ridley
  • 33,766
  • 35
  • 123
  • 197
-1

OperationContext.Current should have a property for this IIRC

abatishchev
  • 98,240
  • 88
  • 296
  • 433
Krzysztof Kozmic
  • 27,267
  • 12
  • 73
  • 115