Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
181 views
in Technique[技术] by (71.8m points)

c# - possible GetObjectsOfType replacement

I have this small piece of code

var idObjects = Spring.Context.Support.ContextRegistry.GetContext()
                      .GetObjectsOfType(typeof (ICustomInterfaceThatDoesSomething));
foreach (ICustomInterfaceThatDoesSomething icitds in idObjects.Values)
      icitds.DoSomething();

Is there a way i can avoid this by having spring.net automatically inject the singletons to a property i declare, like an array of ICustomInterfaceThatDoesSomething?

The only reason i want something like this is because i want to kill the .dll dependency on the project and this is the single point of usage.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could also use method injection:

In sharedLib:

public class MyService
{
    public void ProcessAll()
    {
      foreach (ICustomInterfaceThatDoesSomething icitds in GetAllImplementers())
        icitds.DoSomething();
    }

    protected virtual IEnumerable<ICustomInterfaceThatDoesSomething> 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<ICustomInterfaceThatDoesSomething>(); 
    }
}

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

public class ServiceLocatorImplementer : IMethodReplacer
{
    protected IEnumerable<ICustomInterfaceThatDoesSomething> GetAllImplementers()
    {
        var idObjects = Spring.Context.Support.ContextRegistry.GetContext()
            .GetObjectsOfType(typeof(ICustomInterfaceThatDoesSomething));

        return idObjects.Values.Cast<ICustomInterfaceThatDoesSomething>();
    }

    public object Implement(object target, MethodInfo method, object[] arguments)
    {
        return GetAllImplementers();
    }
}

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

  <objects>

    <object name="serviceLocator" 
            type="WebApp.ServiceLocatorImplementer, WebApp" />

    <object name="service" type="SharedLib.MyService, SharedLib">
      <replaced-method name="GetAllImplementers" replacer="serviceLocator" />
    </object>

  </objects>

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...