possible GetObjectsOfType replacement

前端 未结 4 598
-上瘾入骨i
-上瘾入骨i 2020-12-12 03:08

I have this small piece of code

var idObjects = Spring.Context.Support.ContextRegistry.GetContext()
                      .GetObjectsOfType(typeof (ICustomIn         


        
4条回答
  •  一整个雨季
    2020-12-12 03:54

    I'll leave this answer here for future reference, but I like my other answer better.

    The original answer is rather lenghty and very specific to the example in the question.

    I don't think there is a configuration equivalent to GetObjectsOfType(...).

    However, isn't it very easy to get rid of the Spring.net dependency?

    Let me see if I understand correctly:

    // sharedLib contains ICustomInterfaceThatDoesSomething
    // by "-->" I mean "depends on"
    
    webApp --> Spring.Core, Spring.Web
    webApp --> sharedLib  
    
    sharedLib --> Spring.Core  // only to call GetObjectsOfType(...) on Spring container
    

    We want to get rid of the last dependency, because we want to be able to use sharedLib in combination with another DI container. In sharedLib we have a class that needs to signal all ICustomInterfaceThatDoesSomething implementations to do something. For this purpose I'd create:

    MySomethingManager
    {
      public MySomethingManager() {}
    
      public MySomethingManager(IMySomethingDoerProvider prov) 
      { // init SomethingDoers }
    
      IList SomethingDoers { get; set; }
    
      void SignalAllToDoSomething()
      {
        foreach (var doer in Provider.SomethingDoers )
          doer.DoSomething();
      }
    }
    
    IMySomethingDoerProvider
    {
      IList GetAll();
    }
    

    MySomethingManager used to contain the Spring dependency, but now it's Spring Free. Now I have two options when wiring up sharedLib with regard to MySomethingManager:

    1. using property injection on MySomethingManager.SomethingDoers with a List
    2. using constructor injection with an IMySomethingDoerProvider implementation

    Both can be done using Spring and many other DI containers. You can use the first approach if you don't mind listing all ICustomInterfaceThatDoesSomething in the configuration.

    If you want magical GetObjectsOfType(...) code, you can use the features of your DI container to create a IMySomethingDoerProvider.

    When using Spring, the second approach would require to create:

    MySomethingDoerSpringProvider: IMySomethingDoerProvider
    {
      IList GetAll() 
      {
        // use Spring.Context.Support.ContextRegistry.GetContext()
        //                  .GetObjectsOfType(typeof (ICustomInterfaceThatDoesSomething));
      }
    }
    

    Which you can place in a project that depends on sharedLib. Since your webApp already depends on Spring.Core, you could place MyProvider there to get you started quickly.

    Notes

    If DoSomething is called once per instance, you might consider specifying an initialization method instead.

提交回复
热议问题