possible GetObjectsOfType replacement

前端 未结 4 603
-上瘾入骨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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-12 03:43

    You could also use method injection:

    In sharedLib:

    public class MyService
    {
        public void ProcessAll()
        {
          foreach (ICustomInterfaceThatDoesSomething icitds in GetAllImplementers())
            icitds.DoSomething();
        }
    
        protected virtual IEnumerable GetAllImplementers()
        {
          // note that the Spring dependency is gone
          // you can also make this method abstract, 
          // or create a more useful default implementation
          return new List(); 
        }
    }
    

    In the web app add a class that implements GetAllImplementers():

    public class ServiceLocatorImplementer : IMethodReplacer
    {
        protected IEnumerable GetAllImplementers()
        {
            var idObjects = Spring.Context.Support.ContextRegistry.GetContext()
                .GetObjectsOfType(typeof(ICustomInterfaceThatDoesSomething));
    
            return idObjects.Values.Cast();
        }
    
        public object Implement(object target, MethodInfo method, object[] arguments)
        {
            return GetAllImplementers();
        }
    }
    

    And configure method injection in you web app's object definitions:

      
    
        
    
        
          
        
    
      
    
    
    

    I do feel that it would be better to use the CommonServiceLocator (since service location is what you're doing), but using method injection this way, you don't need to introduce an additional reference to SharedLib.

    提交回复
    热议问题