views:

138

answers:

2

I've been thinking about the IApplicationContext.GetObject(string name) method and it seems to rely fairly heavily on magic strings to get objects from the application context. With other containers like StructureMap you can use generics to specify the configuration and request objects but is there a better way than using strings with the Spring.Net IoC container to request objects from the ApplicationContext?

A: 

You could have a wrapper that you call, taking a generic type parameter.

Something like this:

public void MyMethod()
{
    IMyService myService = ApplicationContextWrapper.Resolve<IMyService>();
}


public static class ApplicationContextWrapper
{
    public static T Resolve<T>()
    {
        return ApplicationContext.Resolve<T>(typeof(T).Name);
    }
}

Not as good as some of the other IoC contatiners, but at least you will get some kind of compiler support.

walkthewalk
A: 

Spring supports the CommonServiceLocator via an adapter. This interface has the API you expected and you also compile against the common service locator so you can switch IoC containers if you want to without having to modify existing code.

tobsen