dI.Hook – How to retrieve an object of hook?

If you are new to dI.Hook, please visit the di.Hook Product Page for Overview, Release Version and Source Code.

Some posts you might want to read would be:

  1. How to create a HookRepository?
  2. How to add hooks to HookRepository?
  3. How to add hooks via configuration file to a HookRepository?
  4. How to invoke all hooks using dI.Hook?
  5. How to invoke hooks that satisfy a condition?

So this is the sixth article in the series which will deal with retrieving one or more hook objects instead of just invoking them.

Step 1 – Creating a repository and add hooks into a repository

The first decision in creating a hook repository is to think whether you want to have lazy loading or not.  Once you have decided you can go through the steps – Creating a Hook Repository using dI.Hook

Be selective in adding hooks into a repository if you plan to invoke all of them at one go.  If you are thinking of manually adding hooks to a repository, would suggest going through – Adding hooks manually into a repository.  However, if you are planning to load them through configuration you can read – Loading a configuration set of hooks into repository

Step 2 – Getting a IHook Object from repository

 

Method One – Getting hook object of a specific type

 

Getting hook by Type
[TestMethod] public void Test_Standard_GetHookByType()
{
    var hooksRetrieved = hookRepository.Get(typeof(LogHook));
    Assert.AreEqual(1, hooksRetrieved.Length);
}

 

The above method will return all the hooks that match the type of LogHook.  Now say for example, the repository was created using code below

Two hooks of same type
LogHook logHook1 = new LogHook(); /* Default Guid, Name */
LogHook logHook2 = new LogHook();
logHook2.Name = "LogHook2";

hookRepository.Add(new[] { logHook1, logHook2 });

 

The code hookRepository.Get(typeof(LogHook)); would return the value 2.

Method Two – Getting hook object based on some condition

 

Getting hook by a predicate
[TestMethod] public void Test_Standard_GetHookByName()
{
    var hooksRetrieved = hookRepository.Get(x => x.Name != null && x.Name.Contains("Log"));
    Assert.AreEqual(1, hooksRetrieved.Length);
}

Using the above method, you can query on the hook collection and returns the hook objects in an IEnumerable collection.

Method Three – Getting all hooks in a repository

This is fairly simple.  You can access the collection Hooks in the repository to get all the hooks added in the repository

Getting all hooks
[TestMethod] public void Test_Standard_GetAllHooks()
{
    var hooksRetrieved = hookRepository.Hooks;
    Assert.AreEqual(2, hooksRetrieved.Length);
}

Related Posts: