Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...